android和ios GoogleMap画导航线路图 路径规划(Directions)
本文适合 【android ios】下的google Map 开发
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
/*** 通过起点终点,组合成url* * @param origin* @param dest* @return*/private String getDirectionsUrl(LatLng origin, LatLng dest) {// Origin of routeString str_origin = "origin=" + origin.latitude + ","+ origin.longitude;// Destination of routeString str_dest = "destination=" + dest.latitude + "," + dest.longitude;// Sensor enabledString sensor = "sensor=false";// Travelling ModeString mode = "mode=driving";//waypoints,116.32885,40.036675String waypointLatLng = "waypoints="+"40.036675"+","+"116.32885";// Building the parameters to the web serviceString parameters = str_origin + "&" + str_dest + "&" + sensor + "&"+ mode+"&"+waypointLatLng;// Output formatString output = "json";// Building the url to the web serviceString url = "https://maps.googleapis.com/maps/api/directions/"+ output + "?" + parameters;System.out.println("getDerectionsURL--->: " + url);return url;}
该方法传递了起点,终点的经纬度,然后组合成了网页请求时用到的URL
1.2.2downloadUrl
/** A method to download json data from url */private String downloadUrl(String strUrl) throws IOException {String data = "";InputStream iStream = null;HttpURLConnection urlConnection = null;try {URL url = new URL(strUrl);// Creating an http connection to communicate with urlurlConnection = (HttpURLConnection) url.openConnection();// Connecting to urlurlConnection.connect();// Reading data from urliStream = 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
// Fetches data from url passedprivate class DownloadTask extends AsyncTask<String, Void, String> {// Downloading data in non-ui thread@Overrideprotected String doInBackground(String... url) {// For storing data from web serviceString data = "";try {// Fetching the data from web servicedata = downloadUrl(url[0]);} catch (Exception e) {Log.d("Background Task", e.toString());}return data;}// Executes in UI thread, after the execution of// doInBackground()@Overrideprotected void onPostExecute(String result) {super.onPostExecute(result);ParserTask parserTask = new ParserTask();// Invokes the thread for parsing the JSON dataparserTask.execute(result);}}
使用异步操作AsynTask实现downurl json 数据
1.2.4ParserTask
/** A class to parse the Google Places in JSON format */private class ParserTask extendsAsyncTask<String, Integer, List<List<HashMap<String, String>>>> {// Parsing the data in non-ui thread@Overrideprotected 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();// Starts parsing dataroutes = parser.parse(jObject);System.out.println("do in background:" + routes);} catch (Exception e) {e.printStackTrace();}return routes;}// Executes in UI thread, after the parsing process@Overrideprotected void onPostExecute(List<List<HashMap<String, String>>> result) {ArrayList<LatLng> points = null;PolylineOptions lineOptions = null;MarkerOptions markerOptions = new MarkerOptions();// Traversing through all the routesfor (int i = 0; i < result.size(); i++) {points = new ArrayList<LatLng>();lineOptions = new PolylineOptions();// Fetching i-th routeList<HashMap<String, String>> path = result.get(i);// Fetching all the points in i-th routefor (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 LineOptionslineOptions.addAll(points);lineOptions.width(3);// Changing the color polyline according to the modelineOptions.color(Color.BLUE);}// Drawing polyline in the Google Map for the i-th routemGoogleMap.addPolyline(lineOptions);}}
异步操作,转换得到的 Google Place json数据,然后显示在google map上。
1.2.5 DirectionsJSONParser
public class DirectionsJSONParser {/*** Receives a JSONObject and returns a list of lists containing latitude and* longitude*/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");/** Traversing all routes */for (int i = 0; i < jRoutes.length(); i++) {jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");List path = new ArrayList<HashMap<String, String>>();/** Traversing all legs */for (int j = 0; j < jLegs.length(); j++) {jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");/** Traversing all steps */for (int k = 0; k < jSteps.length(); k++) {String polyline = "";polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");List<LatLng> list = decodePoly(polyline);/** Traversing 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("lng",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 points Courtesy :* jeffreysambells.com/2010/05/27* /decoding-polylines-from-google-maps-direction-api-with-java* */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;}
}
效果图
红色的线为驾车线路
蓝色的线为步行线路
1.3 URL解析
下面是获取的uil的格式:http://maps.googleapis.com/maps/api/directions/[json|xml]?[params];
有两种输出格式分别是json和xml;
params如下:
destination (必要)您要计算导航路径的终止位置,可以是地址或经纬度。
mode(选用,默认值:driving)指定计算导航时使用的交通模式。
driving表示使用标准行车导航。
walking 要求使用人行道及行人步行导航。
bicycling 要求使用自行车导航。(只适用于美国)
waypoints (选用) 指定导航路径要经过的地点。地点可以指定为经纬度坐标或可进行地理编码的地址。
alternatives (选用)true 时,表示请求导航的回应中提供一个以上的路线。这个可能延长服务器的请求耗时。
avoid(选用) 表示导航路径要避开的地点。这个参数可以是下面的2个值︰
tolls 表示路径避开收费站。
highways 表示路径避开高速公路。
units (选用)指定显示的单位。
metric 使用标准单位,公里和公尺。
imperial 使用英式单位,英里和英尺。
region (选用)将区域代码指定为ccTLD([顶层网域])的两位字元值。
language (选用)路径传回时使用的语言。如果系统不支持设置的语言,那么系统会使用浏览器设置的语言进行返回。
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的轨迹对比图
1.5综述
android和ios GoogleMap画导航线路图 路径规划(Directions)相关推荐
- android GoogleMap画导航线路图 路径规划(Directions)
转自:http://blog.csdn.net/mad1989/article/details/9734667 1.0 GoogleMap路径规划 Google Mapandroid版和IOS版的SD ...
- android GoogleMap画导航线路图 路径规划
最近一个项目要给老外用,用的googlemap,做一些小demo: Google Mapandroid版和IOS版的SDK都没有集成路径规划的相关API,若要实现,只能通过http链接请求URL,携带 ...
- android创建googlemap基础教程和画导航线路图
GoogleMap android API v2:https://developers.google.com/maps/documentation/android/start?hl=zh-CN 链接 ...
- Android集成百度地图接口,实现定位+路径规划。新手教程
本文主要内容包括:如何根据百度地图接口实现定位,并实现从A到B的路径规划功能(驾车,公交,步行).本文主要提供给新手参考,如果有错误希望博友们指出以便及时改正. 1.申请百度地图SDK的密钥(填写安全 ...
- 百度地图SDK导航(路径规划+实时导航)
百度地图导航的官网:http://developer.baidu.com/map/index.php?title=android-navsdk 里面的demo写的非常详细 ,我主要说一下我个人遇到的问 ...
- 机器人学习NO2.导航和路径规划
导航技术前言: 导航技术的移动机器人技术的核心和关键技术.自主移动机器人的导航就是让机器人可以自主按照内部预定的信息,或者依据传感器获取外部环境进行相应的引导,从而规划出一条适合机器人在环境中行走的 ...
- python:基于matplotlib在坐标轴上画出车辆路径规划示意图(箭头、中文图例)
车辆路径规划问题的研究一般较常遇到需要画出车辆路径示意图,已知有每辆车的真实坐标序列,那么如何利用在一个空白的坐标轴上画出路径呢? 1.准备 1.1 matplotlib引入 一般情况下只引入plt就 ...
- 常用的地图导航和路径规划算法
作者:李传学 链接:https://www.zhihu.com/question/24870090/answer/73834896 来源:知乎 著作权归作者所有.商业转载请联系作者获得授权,非商业转载 ...
- iOS调用第三方导航和线路规划
线路规划: https://blog.csdn.net/qq_19979539/article/details/51938995 百度地图:baidumap: 高德地图:iosamap: 腾讯地图:q ...
最新文章
- MySQL5.6 主从复制配置
- 设计模式--程序猿必备面向对象设计原则
- *【HDU - 1517】【POJ - 2505】A Multiplication Game(博弈,递推找规律或SG函数)
- 【机器学习】梯度下降原理
- Appium+PythonUI自动化之webdriver 的三种等待方式(强制等待、隐式等待、显示等待)
- android内容协调,理清Android协调布局CoordinatorLayout的摆放位置及特殊属性。
- 牛客网-内心里的一把火
- Backbone学习日记第二集——Model
- 实现AutoCAD和ArcGIS进行并发和互编辑操作
- 七日Python之路--第十一天
- Video Copilot VCReflect for Mac/win (AE倒影插件) 支持2022多帧渲染​
- Cocos Creator大厅+子游戏模式
- 在线XML转JSON工具
- 【2021】15天通过阿里云云计算架构师认证考试(ACE)- 经验分享
- camera具体曝光时间readout时间出图时间
- jpeg-snoo-图片信息分析工具
- 最近经常看到网上程序员被抓,如何避免面向监狱编程!?
- 云管边端架构图_边缘云平台架构与应用案例分析
- html5 3d柱形,Highcharts 3D柱形图
- 国内外主流文档搜索网站