在 Google Maps v2 Android 上突出显示指定路线 [英] Highlight a specified route on Google Maps v2 Android
问题描述
是的,所以我目前在我的应用中使用 Google Directions API 来检索两个位置之间的路线.
Right, so I'm currently using the Google Directions API in my app to retrieve the route between two locations.
当我发送路线方向请求时,我会在 JSON 中检索有关路线的许多详细信息,包括路线沿线每条道路的名称、它们相应的起点和终点经纬度坐标以及它们的折线值.
When I send a request for a route directions, I retrieve a number of details in JSON regarding the route including the names of every road along the route, their corresponding start and end lat-long co-ordinates, and their polyline value.
例如:如果我发送请求 http://maps.googleapis.com/maps/api/directions/json?origin=redfern+ave,+dublin&destination=limetree+ave,+dublin&sensor=false 在两条道路之间,我得到以下 JSON 响应(沿路线的一条道路的输出).
For example: If I send the request http://maps.googleapis.com/maps/api/directions/json?origin=redfern+ave,+dublin&destination=limetree+ave,+dublin&sensor=false between two roads, I get the following JSON response (output for one road along route).
{
"distance" : {
"text" : "0.2 km",
"value" : 203
},
"duration" : {
"text" : "1 min",
"value" : 18
},
"end_location" : {
"lat" : 53.435250,
"lng" : -6.132140000000001
},
"html_instructions" : "Head u003cbu003eeastu003c/bu003e on u003cbu003eRedfern Ave.u003c/bu003e toward u003cbu003eMartello Courtu003c/bu003e",
**"polyline" : {
"points" : "woceIvgmd@O}DOkDQqF"**
},
到目前为止,我的应用程序解析了这些信息,并在列表视图中简单地列出了道路和方向,如下所示:
So far my application parses this information and simply lists the roads and directions in a list view like this:
我想做的是在地图上突出显示从 A 到 B 的整条路线,但是我在网上没有发现任何关于如何在新的 Google Maps API v2 上执行此操作的有用信息.我看到在 Google Maps v2 上使用折线而不是叠加来绘制线条,但是据我所知,它们只绘制对我无用的直线.无论如何,是否可以使用我掌握的信息突出显示路线(道路名称、起点和终点经纬度坐标、折线点?感谢任何帮助.
What I want to do it highlight the whole route from A to B on a map, however I've found nothing useful online on how to do this on the new Google Maps API v2. I see that polyline's are used instead of overlays to draw lines on Google Maps v2, however from what I can tell, they only draw straight lines which is useless for me. Is there anyway of highlighting the route using the information I have at my disposal (road names, start & end lat-long co-ordinates, polyline points? Any help is appreciated.
此外,我看到响应中有一个折线"值,这可能很有用,但我不知道如何解析或使用这些信息.有谁知道我如何理解这个值来绘制折线?
Also, I see there is a 'polyline' value in the response which could be useful but I can't work out how to parse or use this bit of information. Does anyone know how I can make sense of this value to plot a polyline?
**"polyline" : {
"points" : "woceIvgmd@O}DOkDQqF"**
我的解决方案代码在下面的答案中提供.
My solution code is provided in my answer below.
推荐答案
经过多次反复试验,我终于设法让它工作了!它现在在地图上完全突出显示从 A 到 B 的指定路线(如下面的屏幕截图所示).我还为将来可能需要的人提供了我的代码.
I finally managed to get it working after a lot of trial and error! It now fully highlights a specified route from A to B on a map (as seen in my screenshot below). I have also thrown in my code for anyone who may need it in future.
public class PolyMap extends Activity {
ProgressDialog pDialog;
GoogleMap map;
List<LatLng> polyz;
JSONArray array;
static final LatLng DUBLIN = new LatLng(53.344103999999990000,
-6.267493699999932000);
@SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(DUBLIN, 15));
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
new GetDirection().execute();
}
class GetDirection extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PolyMap.this);
pDialog.setMessage("Loading route. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
Intent i = getIntent();
String startLocation = i.getStringExtra("startLoc");
String endLocation = i.getStringExtra("endLoc");
startLocation = startLocation.replace(" ", "+");
endLocation = endLocation.replace(" ", "+");;
String stringUrl = "http://maps.googleapis.com/maps/api/directions/json?origin=" + startLocation + ",+dublin&destination=" + endLocation + ",+dublin&sensor=false";
StringBuilder response = new StringBuilder();
try {
URL url = new URL(stringUrl);
HttpURLConnection httpconn = (HttpURLConnection) url
.openConnection();
if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader input = new BufferedReader(
new InputStreamReader(httpconn.getInputStream()),
8192);
String strLine = null;
while ((strLine = input.readLine()) != null) {
response.append(strLine);
}
input.close();
}
String jsonOutput = response.toString();
JSONObject jsonObject = new JSONObject(jsonOutput);
// routesArray contains ALL routes
JSONArray routesArray = jsonObject.getJSONArray("routes");
// Grab the first route
JSONObject route = routesArray.getJSONObject(0);
JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyz = decodePoly(polyline);
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(String file_url) {
for (int i = 0; i < polyz.size() - 1; i++) {
LatLng src = polyz.get(i);
LatLng dest = polyz.get(i + 1);
Polyline line = map.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude),
new LatLng(dest.latitude, dest.longitude))
.width(2).color(Color.RED).geodesic(true));
}
pDialog.dismiss();
}
}
/* Method to decode polyline points */
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
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;
}
}
这篇关于在 Google Maps v2 Android 上突出显示指定路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!