本文适合 【Android iOS】下的google Map 开发
转自:http://blog.csdn.NET/mad1989/article/details/9734667
1.0 GoogleMap路径规划
Google Mapandroid版和IOS版的SDK都没有集成路径规划的相关API,若要实现,只能通过http链接请求URL,携带起点终点经纬度,得到返回集合,在地图中展示。
Google Directions API :https://developers.google.com/maps/documentation/directions/#Waypoints
Directions Service:https://developers.google.com/maps/documentation/javascript/directions#DirectionsRequests
1.1 请求链接
举个例子:
https://maps.googleapis.com/maps/api/directions/json?origin=39.99709957757345,116.31184045225382&destination=39.949158391497214,116.4154639095068&sensor=false&mode=driving
origin=起点经纬度 destination=终点经纬度
返回的json数据(网页打开):

1.2 android实例
1.2.1 getDestinationURL
代码:
-
-
-
-
-
-
-
- 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 mode = "mode=driving";
-
-
- String waypointLatLng = "waypoints="+"40.036675"+","+"116.32885";
-
-
- String parameters = str_origin + "&" + str_dest + "&" + sensor + "&"
- + mode+"&"+waypointLatLng;
-
-
- String output = "json";
-
-
- String url = "https://maps.googleapis.com/maps/api/directions/"
- + output + "?" + parameters;
- System.out.println("getDerectionsURL--->: " + url);
- return url;
- }
该方法传递了起点,终点的经纬度,然后组合成了网页请求时用到的URL
1.2.2downloadUrl
【本文是以json格式作为result结果,如果想要以xml形式为Result结果,请步:
http://blog.csdn.net/mad1989/article/details/10008009】
源码:
-
- 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();
- }
- System.out.println("url:" + strUrl + "----> downloadurl:" + data);
- return data;
- }
该方法通过携带经纬度的url请求得到json数据
1.2.3downloadTask
-
- private class DownloadTask extends AsyncTask {
-
-
- @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);
- }
- }
使用异步操作AsynTask实现downurl json 数据
1.2.4ParserTask
-
- private class ParserTask extends
- AsyncTask>>> {
-
-
- @Override
- protected List
>> doInBackground(
- String... jsonData) {
-
- JSONObject jObject;
- List
>> routes = null;
-
- try {
- jObject = new JSONObject(jsonData[0]);
- DirectionsJSONParser parser = new DirectionsJSONParser();
-
-
- routes = parser.parse(jObject);
- System.out.println("do in background:" + routes);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return routes;
- }
-
-
- @Override
- protected void onPostExecute(List
>> result) {
- ArrayList points = null;
- PolylineOptions lineOptions = null;
- MarkerOptions markerOptions = new MarkerOptions();
-
-
- for (int i = 0; i < result.size(); i++) {
- points = new ArrayList();
- lineOptions = new PolylineOptions();
-
-
- List> path = result.get(i);
-
-
- for (int j = 0; j < path.size(); j++) {
- HashMap 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(3);
-
-
- lineOptions.color(Color.BLUE);
- }
-
-
- mGoogleMap.addPolyline(lineOptions);
- }
- }
异步操作,转换得到的 Google Place json数据,然后显示在google map上。
1.2.5 DirectionsJSONParser
- public class DirectionsJSONParser {
-
-
-
-
- public List
>> parse(JSONObject jObject) {
-
- List
>> routes = new ArrayList>>();
- JSONArray jRoutes = null;
- JSONArray jLegs = null;
- JSONArray jSteps = null;
-
- try {
-
- jRoutes = jObject.getJSONArray("routes");
-
-
- for (int i = 0; i < jRoutes.length(); i++) {
- jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
- List path = new ArrayList>();
-
-
- for (int j = 0; j < jLegs.length(); j++) {
- jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
-
-
- for (int k = 0; k < jSteps.length(); k++) {
- String polyline = "";
- polyline = (String) ((JSONObject) ((JSONObject) jSteps
- .get(k)).get("polyline")).get("points");
- List list = decodePoly(polyline);
-
-
- for (int l = 0; l < list.size(); l++) {
- HashMap hm = new HashMap();
- hm.put("lat",
- Double.toString(((LatLng) list.get(l)).latitude));
- hm.put("lng",
- Double.toString(((LatLng) list.get(l)).longitude));
- path.add(hm);
- }
- }
- routes.add(path);
- }
- }
- } catch (JSONException e) {
- e.printStackTrace();
- } catch (Exception e) {
- }
- return routes;
- }
-
-
-
-
-
-
- private List decodePoly(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;
- }
- }
效果图
红色的线为驾车线路
蓝色的线为步行线路
1.3 URL解析
导航的路径信息可以通过Http获取也可以通过Https获取;两者的url是相同的,不同的是https比http安全而已。
下面是获取的uil的格式:http://maps.googleapis.com/maps/api/directions/[json|xml]?[params];
有两种输出格式分别是json和xml;
params如下:
origin(必要)您要计算导航路径的起始位置,可以是地址或经纬度。
destination (必要)您要计算导航路径的终止位置,可以是地址或经纬度。
mode(选用,默认值:driving)指定计算导航时使用的交通模式。
driving表示使用标准行车导航。
walking 要求使用人行道及行人步行导航。
bicycling 要求使用自行车导航。(只适用于美国)
waypoints (选用) 指定导航路径要经过的地点。地点可以指定为经纬度坐标或可进行地理编码的地址。
alternatives (选用)true 时,表示请求导航的回应中提供一个以上的路线。这个可能延长服务器的请求耗时。
avoid(选用) 表示导航路径要避开的地点。这个参数可以是下面的2个值︰
tolls 表示路径避开收费站。
highways 表示路径避开高速公路。
units (选用)指定显示的单位。
metric 使用标准单位,公里和公尺。
imperial 使用英式单位,英里和英尺。
region (选用)将区域代码指定为ccTLD([顶层网域])的两位字元值。
language (选用)路径传回时使用的语言。如果系统不支持设置的语言,那么系统会使用浏览器设置的语言进行返回。
zh-CN 简体汉语
en-US 英语
sensor (必要) 指出导航的请求设备是否附有位置感应器。这个值必须是 true 或 false。
以下是Google Directions API提供的2个URL的示例供参考:
http://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA&sensor=false
http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false
以上的例子是根据地点名称来获取导航路径的方式,下面说明如何使用经纬度的方式来获取导航路径:
示例:http://maps.googleapis.com/maps/api/directions/json?origin=37.458060333333336%2c118.49971400000001&destination=37.458260333333336%2c118.50971400000001&sensor=false
1.4 携带waypoints的轨迹对比图
如果我们的导航路线希望通过地图中的某几个地方,则在url中添加一个parmas名称为 waypoints,waypoints只能携带8个。该属性我已经在上边的java代码中添加,可以自己查看。
https://maps.googleapis.com/maps/api/directions/json?origin=39.99709957757345,116.31184045225382&destination=39.949158391497214,116.4154639095068&sensor=false&mode=driving&waypoints=40.036675,116.32885
效果图:
1.5综述
目前来看,循环添加2(或多个)个点的方法,可以减小误差的情况,不过得设置定时器,当上一此循环返回结果后再进行下一次循环(异步回调),这样轨迹查询可能就会耗时一些。Google map 在国内的环境下,路径规划请求的URL有些慢,偶尔timeout还得不到结果。