Android 谷歌地图机器人在当前位置和地点之间的路线
我试图在当前位置和另一个点之间画一条路线。我写的代码可以检查当前位置,也可以在地图上点击地图上的点。目前,程序运行良好, 但我想在当前位置和一个新点(我在地图上添加的点)之间画另一条路线。 下面是我的代码,有人知道我如何在代码中添加这个逻辑吗Android 谷歌地图机器人在当前位置和地点之间的路线,android,google-maps-android-api-2,Android,Google Maps Android Api 2,我试图在当前位置和另一个点之间画一条路线。我写的代码可以检查当前位置,也可以在地图上点击地图上的点。目前,程序运行良好, 但我想在当前位置和一个新点(我在地图上添加的点)之间画另一条路线。 下面是我的代码,有人知道我如何在代码中添加这个逻辑吗 public class GPS extends Activity implements OnMyLocationChangeListener,OnMapClickListener, OnMapLongClickListener, OnM
public class GPS extends Activity implements
OnMyLocationChangeListener,OnMapClickListener,
OnMapLongClickListener, OnMarkerDragListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Circle myCircle;
Location myLocation;
TextView tvLocInfo, GPSLocation;
LatLng latLng;
boolean markerClicked;
ArrayList<LatLng> markerPoints;
Polygon polygon;
public Button btnline;
double Clicklatitude, Clicklongitude, latitude, longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gps);
markerPoints=new ArrayList<LatLng>();
btnline = (Button) findViewById(R.id.button1);
tvLocInfo = (TextView) findViewById(R.id.GpsTxt);
GPSLocation = (TextView) findViewById(R.id.GPSLocation);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment = (MapFragment) myFragmentManager
.findFragmentById(R.id.GpsMap);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setOnMyLocationChangeListener(this);
myMap.setOnMapClickListener(this);
myMap.setOnMapLongClickListener(this);
myMap.setOnMarkerDragListener(this);
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
myMap.setMyLocationEnabled(true);
myMap.setOnMyLocationChangeListener(this);
markerClicked = false;
btnline.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
@Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_LONG)
.show();
} else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}
@Override
public void onMyLocationChange(Location location) {
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
myMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
GPSLocation.setText(latitude + " " + longitude);
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng locLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
double accuracy = location.getAccuracy();
if (myCircle == null) {
CircleOptions circleOptions = new CircleOptions().center(locLatLng)
// set center
.radius(accuracy)
// set radius in meters
.fillColor(Color.RED).strokeColor(Color.BLACK)
.strokeWidth(5);
myCircle = myMap.addCircle(circleOptions);
} else {
myCircle.setCenter(locLatLng);
myCircle.setRadius(accuracy);
}
myMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// myMap.animateCamera(CameraUpdateFactory.newLatLng(locLatLng));
}
@Override
public void onMarkerDrag(Marker arg0) {
// TODO Auto-generated method stub
}
@Override
public void onMarkerDragEnd(Marker arg0) {
// TODO Auto-generated method stub
}
@Override
public void onMarkerDragStart(Marker arg0) {
// TODO Auto-generated method stub
}
@Override
public void onMapLongClick(LatLng point) {
}
@Override
public void onMapClick(LatLng point) {
Clicklatitude = point.latitude;
Clicklongitude = point.longitude;
tvLocInfo.setText(Clicklatitude + " " + Clicklongitude);
if (point != null)
myMap.clear();
myMap.addMarker(new MarkerOptions().position(point).draggable(true));
markerClicked = false;
}
公共类GPS扩展活动工具
OnMyLocationChangeListener,OnMapClickListener,
OnMapLongClickListener,OnMarkerDragListener{
最终int RQS_GooglePlayServices=1;
私人谷歌地图;
圈我的圈;
位置;
TextView tvLocInfo,GPSLocation;
LatLng LatLng;
布尔标记单击;
ArrayList markerPoints;
多边形;
公共按钮btnline;
双击纬度,单击经度,纬度,经度;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(窗口。功能\u无\u标题);
setContentView(R.layout.gps);
markerPoints=newarraylist();
btnline=(按钮)findViewById(R.id.button1);
tvLocInfo=(TextView)findViewById(R.id.GpsTxt);
GPSLocation=(TextView)findViewById(R.id.GPSLocation);
FragmentManager myFragmentManager=getFragmentManager();
MapFragment myMapFragment=(MapFragment)myFragmentManager
.findFragmentById(R.id.GpsMap);
myMap=myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
setOnMyLocationChangeListener(this);
myMap.setOnMapClickListener(这个);
myMap.setOnMapLongClickListener(这个);
setOnMarkerDragListener(this);
myMap.setMapType(GoogleMap.MAP\u TYPE\u NORMAL);
myMap.setMyLocationEnabled(true);
setOnMyLocationChangeListener(this);
markerClicked=false;
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
}
});
}
@凌驾
受保护的void onResume(){
super.onResume();
int resultCode=GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if(resultCode==ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
“iGoogle PlayServicesAvailable SUCCESS”,祝酒词。长度(长)
.show();
}否则{
GooglePlayServicesUtil.getErrorDialog(结果代码,此,
RQS_谷歌游戏服务);
}
}
@凌驾
公共void onMyLocationChange(位置){
纬度=位置。getLatitude();
//正在获取当前位置的经度
longitude=location.getLongitude();
//为当前位置创建LatLng对象
latLng=新latLng(纬度、经度);
//在谷歌地图中显示当前位置
myMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//放大谷歌地图
GPSLocation.setText(纬度+“”+经度);
myMap.setMapType(GoogleMap.MAP\u TYPE\u NORMAL);
LatLng LOCLATLING=新LatLng(location.getLatitude(),
location.getLongitude());
双精度=位置。getAccurance();
如果(myCircle==null){
CircleOptions CircleOptions=新CircleOptions().center(Localng)
//居中
.半径(精度)
//以米为单位设置半径
.fillColor(颜色.红色).strokeColor(颜色.黑色)
.冲程宽度(5);
myCircle=myMap.addCircle(circleOptions);
}否则{
myCircle.setCenter(locLatLng);
myCircle.setRadius(精度);
}
myMap.animateCamera(CameraUpdateFactory.zoomTo(15));
//myMap.animateCamera(CameraUpdateFactory.newLatLng(locLatLng));
}
@凌驾
MarkerDrag上的公共空白(标记arg0){
//TODO自动生成的方法存根
}
@凌驾
MarkerDragEnd上的公共无效(标记arg0){
//TODO自动生成的方法存根
}
@凌驾
MarkerDragStart上的公共无效(标记arg0){
//TODO自动生成的方法存根
}
@凌驾
在马普隆喀喇克(LatLng点)上的公共空隙{
}
@凌驾
公共空区(停车点){
单击纬度=点。纬度;
单击经度=点。经度;
tvLocInfo.setText(单击纬度+“”+单击经度);
如果(点!=null)
myMap.clear();
addMarker(newmarkeroptions().position(point).draggable(true));
markerClicked=false;
}
}
我想得到这样的结果通过这段代码我得到了同样的结果。这将是一些与您尝试的代码不同的代码 首先,用这两件事来实现你的类
在MapReadyCallback、LocationListener上实现
当您实现OnMapReadyCallback时,将调用预定义方法
“在四月一日”
为了获取当前位置,我制作了一个方法,当您实现LocationListener时
它将为您提供名为“onLocationChanged”的预定义方法
获取当前位置和目标之间的路径。。
您需要将数据传递到GoogleAPI,它将写入一个JSON结果
您必须获得此结果并将其显示为多段线(以显示路径)
private void exeTask(){
字符串originPl=“origin=“+originLati.toString()+”,“+originLong.toString();
String destipl=“destination=“+destiLati.toString()+”,“+destiLong.toString();
字符串sensor=“sensor false”;
String mode=“模式驱动”;
字符串参数=originPl+“&”+destipl+“&”+sensor+“&”+mode+“&key='Your_API_key';
最终url=”https://maps.googleapis.com/maps/api/directions/json?“+param;
//Log.d(最终url,“这是创建的url”);
TaskRequestDirections TaskRequestDirections=新TaskRequestDirections();
taskRequestDirections.execute(最终url);
}
私有字符串请求方向(字符串请求URL)引发IOException{
字符串responseString=“”;
InputStream InputStream=null;
@Override
public void onMapReady(GoogleMap googleMap) {
destiLati = 40.728634;
destiLong = -73.974956;
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
// Add a marker in Destination/Desire point and move the camera
DestinationPoint = new LatLng(destiLati, destiLong);
mMap.addMarker(new MarkerOptions().position(DestinationPoint).title("Destination
Point")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
//To move camera to Desination Location.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(DestinationPoint, 10));
//Permission To get Current Location
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
private void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, this);
}
catch(SecurityException e) {
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location location) {
//This thing will get User's current location
originLati = location.getLatitude();
originLong = location.getLongitude();
exeTask();
//Log.d(originLati.toString(),"This is the value of orginalati" + originLati.toString() + " " + originLong.toString());
}
private void exeTask(){
String originPl = "origin=" + originLati.toString() + "," + originLong.toString();
String destipl = "destination=" + destiLati.toString() + "," + destiLong.toString();
String sensor = "sensor-false";
String mode = "mode-driving";
String param = originPl + "&" + destipl + "&" + sensor + "&" + mode + "&key='Your_API_KEY'";
final_url = "https://maps.googleapis.com/maps/api/directions/json?" + param;
//Log.d(final_url,"This is the URL which was created");
TaskRequestDirections taskRequestDirections = new TaskRequestDirections();
taskRequestDirections.execute(final_url);
}
private String requestDirection(String reqUrl) throws IOException {
String responseString = "";
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try{
URL url = new URL(reqUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
//TO get the in String format response result
inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
responseString = stringBuffer.toString();
bufferedReader.close();
inputStreamReader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
httpURLConnection.disconnect();
}
return responseString;
}
public class TaskRequestDirections extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
String responseString = "";
try {
responseString = requestDirection(strings[0]);
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Parse json/ Data will come from here..
TaskParser taskParser = new TaskParser();
taskParser.execute(s);
}
}
public class TaskParser extends AsyncTask<String, Void, List<List<HashMap<String, String>>> > {
@Override
protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
JSONObject jsonObject = null;
List<List<HashMap<String, String>>> routes = null;
try {
jsonObject = new JSONObject(strings[0]);
DirectionsParser directionsParser = new DirectionsParser();
routes = directionsParser.parse(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
return routes;
}
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
//To get list route and display it into the map
ArrayList points = null;
PolylineOptions polylineOptions = null;
for (List<HashMap<String, String>> path : lists) {
points = new ArrayList();
polylineOptions = new PolylineOptions();
for (HashMap<String, String> point : path) {
double lat = Double.parseDouble(point.get("lat"));
double lon = Double.parseDouble(point.get("lon"));
points.add(new LatLng(lat,lon));
}
polylineOptions.addAll(points);
polylineOptions.width(10);
polylineOptions.color(Color.BLUE);
polylineOptions.geodesic(true);
}
if (polylineOptions!=null) {
mMap.addPolyline(polylineOptions);
} else {
//Toast.makeText(getApplicationContext(), "Direction not found!", Toast.LENGTH_SHORT).show();
}
}
}
public class DirectionsParser {
/**
* Returns a list of lists containing latitude and longitude from a JSONObject
*/
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
// Loop for all routes
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
//Loop for all legs
for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
//Loop for all steps
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
List list = decodePolyline(polyline);
//Loop for all points
for (int l = 0; l < list.size(); l++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude));
hm.put("lon", Double.toString(((LatLng) list.get(l)).longitude));
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
}
return routes;
}
/**
* Method to decode polyline
* Source : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
*/
private List decodePolyline(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}