对不起我的英语语法!如果您有什么不明白的地方,可以再问我!
我使用 Volley 在 Google 地图中的两点之间绘制一条路径
private void getPath(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
showDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = parser.parse(response);
List<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = routes.get(i);
// Fetching all the points in i-th route
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);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
if (mGoogleMap != null) {
// Drawing polyline in the Google Map for the i-th route
mGoogleMap.addPolyline(lineOptions);
}
hideDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("APP", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hideDialog();
}
});
// Adding request to request queue
App.getInstance().addToRequestQueue(jsonObjReq);
}
此代码工作正常。但现在,我有一个点列表(点数> 2)。
如何绘制经过所有点的路径。
我尝试编写一个 Asyntask 并在 doInBackground() 函数中循环“getPath(x1, x2)”,但它不起作用。
以我的理解:volley 在后台运行,将其放入 Asyntask 中(也在后台运行)??????!!!!!!
首先在地图上绑定点击监听器
googleMap.setOnMapClickListener(this);
然后,将所有点添加到列表中,然后绘制黑白折线。就像我一样 做下面的事情
@Override
public void onMapClick(LatLng latlan) {
latLang.add(latlan);
GeoPoint point = new GeoPoint(latlan.latitude, latlan.longitude);
listPoints.add((IGeoPoint) point);
MarkerOptions marker = new MarkerOptions().position(latlan);
googleMap.addMarker(marker);
if (latLang.size() > 1) {
PolylineOptions polyLine = new PolylineOptions().color(
Color.BLUE).width((float) 7.0);
polyLine.add(latlan);
LatLng previousPoint = latLang.get(latLang.size() - 2);
polyLine.add(previousPoint);
googleMap.addPolyline(polyLine);
}
}