[英]How to draw route more than two points on Google map in android?
I want to display multiple points on a Google map with a route. 我想在带有路线的Google地图上显示多个点。 The points should be dynamic, with input given by the user.
这些点应该是动态的,并由用户给出输入。
The output will look like as given below image : 输出结果如下图所示:
I want to show the driving route between multiple locations in my Android app. 我想在我的Android应用中显示多个位置之间的行车路线。
There are several answers on Stack Overflow itself, and all of them were using the same method. Stack Overflow本身有几个答案,所有这些答案都使用相同的方法。 Get the directions from start point to destination using Google directions API, and draw a polyline across the points returned.
使用Google Directions API获取从起点到目的地的路线,并在返回的点上绘制折线。
I used the below code but it shows the route between only two points. 我使用下面的代码,但它显示了只有两点之间的路线。 However, I want to display the route between multiple points.
但是,我想显示多个点之间的路线。
Thanks in advance. 提前致谢。
private GoogleMap mMap;
ArrayList<LatLng> markerPoints;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
markerPoints = new ArrayList<LatLng>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Button btnDraw = (Button) findViewById(R.id.btn_draw);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
if (markerPoints.size() >= 10) {
return;
}
markerPoints.add(point);
MarkerOptions options = new MarkerOptions();
options.position(point);
if (markerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (markerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
} else {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
}
mMap.addMarker(options);
}
});
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng point) {
mMap.clear();
markerPoints.clear();
}
});
btnDraw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (markerPoints.size() >= 2) {
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
}
});
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String sensor = "sensor=false";
String waypoints = "";
for (int i = 2; i < markerPoints.size(); i++) {
LatLng point = (LatLng) markerPoints.get(i);
if (i == 2)
waypoints = "waypoints=";
waypoints += point.latitude + "," + point.longitude + "|";
}
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + waypoints;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
@SuppressLint("LongLogTag")
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
@Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng AT = new LatLng(20.039413, 74.479977);
mMap.addMarker(new MarkerOptions().position(AT).title("Marker in Yeola"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(AT));
}
In your onPostExecute
in the ParserTask
there is an error which is easily corrected. 在
onPostExecute
中的ParserTask
有一个容易纠正的错误。 In the outer loop, on result.size(), you recreate the lineOptions
variable which means only the very last iteration will get added to the map since your addPolyline
call is outside the loop. 在外部循环中,在result.size()上,重新创建
lineOptions
变量,这意味着只有最后一次迭代才会被添加到地图中,因为你的addPolyline
调用在循环之外。
So you can fix this in two ways but the result is the same: 所以你可以通过两种方式解决这个问题,但结果是一样的:
addPolyline
for each iteration. addPolyline
。 (This seems like your intention.) Since the map doesn't care how the aggregate path is comprised, and since the directions result will be properly terminated for each segment, I prefer (a) as the solution but I listed both. 由于地图不关心如何组成聚合路径,并且由于每个段的路线结果将被正确终止,我更喜欢(a)作为解决方案,但我列出了两者。
To fix with option (a): 要修复选项(a):
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = new ArrayList<>();
PolylineOptions lineOptions = new PolylineOptions();
for (int i = 0; i < result.size(); i++) {
List<HashMap<String, String>> path = result.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
// Drawing polyline in the Google Map for the entire route
mMap.addPolyline(lineOptions);
}
To fix with option (b): 要修复选项(b):
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = new ArrayList<>();
for (int i = 0; i < result.size(); i++) {
points.clear();
PolylineOptions lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.