In this tutorial, we’ll be creating an android application that draws a possible google map route between two points. We’ll be using Google Maps Directions API in our application.

在本教程中,我们将创建一个Android应用程序,该应用程序在两点之间绘制一条可能的Google地图路线。 我们将在应用程序中使用Google Maps Directions API。

Android Google Map –绘图路线 (Android Google Map – Drawing Route)

Create a new Google Map API Key from the API console using the steps demonstrated in this tutorial.

使用本教程中演示的步骤,从API控制台创建新的Google Map API密钥。

Create a New Android Studio Project and select the template as Google Maps Activity. Add the API key inside the google_maps_api.xml file that resides inside debug->res->values folder

创建一个新的Android Studio项目,然后选择模板作为Google Maps Activity 。 将API密钥添加到位于debug-> google_maps_api.xml > values文件夹内的google_maps_api.xml文件中

This is how the application should look if you’re using the latest Android Studio.

如果您使用的是最新的Android Studio,则该应用程序应为这样。

Android Google Maps绘图路径项目结构 (Android Google Maps Drawing Path Project Structure)

The DirectionsJSONParser.java file is the one that parses the locations and returns the route. decodePoly() method is then invoked to get the polyline data that’s later drawn on the map.

DirectionsJSONParser.java文件是解析位置并返回路线的文件。 然后调用decodePoly()方法来获取折线数据,该折线数据稍后会在地图上绘制。

Android Google Maps绘图路线代码 (Android Google Maps Drawing Route Code)

The MainActivity.java code is given below.

MainActivity.java代码如下。

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {private GoogleMap mMap;ArrayList markerPoints= new ArrayList();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_maps);// Obtain the SupportMapFragment and get notified when the map is ready to be used.SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);mapFragment.getMapAsync(this);}@Overridepublic void onMapReady(GoogleMap googleMap) {mMap = googleMap;LatLng sydney = new LatLng(-34, 151);//mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 16));mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {@Overridepublic void onMapClick(LatLng latLng) {if (markerPoints.size() > 1) {markerPoints.clear();mMap.clear();}// Adding new item to the ArrayListmarkerPoints.add(latLng);// Creating MarkerOptionsMarkerOptions options = new MarkerOptions();// Setting the position of the markeroptions.position(latLng);if (markerPoints.size() == 1) {options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));} else if (markerPoints.size() == 2) {options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));}// Add new marker to the Google Map Android API V2mMap.addMarker(options);// Checks, whether start and end locations are capturedif (markerPoints.size() >= 2) {LatLng origin = (LatLng) markerPoints.get(0);LatLng dest = (LatLng) markerPoints.get(1);// Getting URL to the Google Directions APIString url = getDirectionsUrl(origin, dest);DownloadTask downloadTask = new DownloadTask();// Start downloading json data from Google Directions APIdownloadTask.execute(url);}}});}private class DownloadTask extends AsyncTask {@Overrideprotected String doInBackground(String... url) {String data = "";try {data = downloadUrl(url[0]);} catch (Exception e) {Log.d("Background Task", e.toString());}return data;}@Overrideprotected void onPostExecute(String result) {super.onPostExecute(result);ParserTask parserTask = new ParserTask();parserTask.execute(result);}}private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap>>> {// Parsing the data in non-ui thread@Overrideprotected List<List<HashMap>> doInBackground(String... jsonData) {JSONObject jObject;List<List<HashMap>> routes = null;try {jObject = new JSONObject(jsonData[0]);DirectionsJSONParser parser = new DirectionsJSONParser();routes = parser.parse(jObject);} catch (Exception e) {e.printStackTrace();}return routes;}@Overrideprotected void onPostExecute(List<List<HashMap>> 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<HashMap> 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(12);lineOptions.color(Color.RED);lineOptions.geodesic(true);}// Drawing polyline in the Google Map for the i-th routemMap.addPolyline(lineOptions);}}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";String mode = "mode=driving";// Building the parameters to the web serviceString parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;// Output formatString output = "json";// Building the url to the web serviceString url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;return url;}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", e.toString());} finally {iStream.close();urlConnection.disconnect();}return data;}
}

We’ve called an onMapClickListener on the google map object. It’s used to set a marker on the clicked location and store that location in an ArrayList. The ArrayList is used to store the source and destination markers only.
The getDirectionsUrl() is called the Directions API URL with the output and parameters as shown below.

我们在Google地图对象上调用了onMapClickListener 。 它用于在单击的位置上设置标记,并将该位置存储在ArrayList中。 ArrayList仅用于存储源标记和目标标记。
getDirectionsUrl()称为Directions API URL,其输出和参数如下所示。

"https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;

"https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;

The output variable holds a “json” string and the parameter string is created as:
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;

输出变量包含一个“ json”字符串,参数字符串创建为:
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;

We’ve set the mode=driving in the current application.
The other modes of transport are:

我们在当前应用程序中设置了mode = driving
其他运输方式是:

  • driving (default)驾驶(默认)
  • walking步行
  • bicycling单车
  • transit过境

The output of the application is given below:

该应用程序的输出如下:

This brings an end to this tutorial. You can download the final project from the link below, add your own Google Map API key.

本教程到此结束。 您可以从下面的链接下载最终项目,并添加自己的Google Map API密钥。

Download Android Google Maps Draw Route Project下载Android Google Maps Draw Route项目

翻译自: https://www.journaldev.com/13373/android-google-map-drawing-route-two-points

Android Google Map –两点之间的绘图路线相关推荐

  1. Android Google Map实例 - 在地图和卫星图之间切换(Android mapview)

    之前讲述的例子中显示的 为地图模式,如何你想使用类似google earth的卫星图模式显示,如何操作? 在android上将变得非常简单: 增加两个Button按钮和两个对应的Button.OnCl ...

  2. Android Google Map 开发指南(一)解决官方demo显示空白只展示google logo问题

    这两天一直在做google map接入前的准备工作 特此在这里将自己在加载官方demo时出现的问题以及详细的接入步骤进行记录,已免后者踩坑 注:项目实际运行时不要使用虚拟机 因为电脑ip和虚拟机ip不 ...

  3. android google map key,android google map api key取得?

    我有一个项目的谷歌地图apikey现在我想要另一个项目的apikey和这个项目的keystore是在一个不同的地方.我的第一个cmd:android google map api key取得? &qu ...

  4. Android Google Map开发指南(三)百度地图、谷歌地图自如切换

    如果你是刚开始接触谷歌地图的话,推荐你先看一下文章: Android Google Map 开发指南(一)解决官方demo显示空白只展示google logo问题 Android Google Map ...

  5. Android Google Map集成以及部分功能的实现

    最近公司在做一个海外项目 有Google map的使用 话不多说进入正题: 首先vpn   手机必须能支持Google play服务 (我做的时候Google play服务要想安装手机必须root,但 ...

  6. android google map研究

    2019独角兽企业重金招聘Python工程师标准>>> 研究了一天,最后居然卡在了获取本地位置上,不知道是不是我的G330D问题,反正网络位置是获取不了,看来得用百度地图试试,还是总 ...

  7. android Google Map API V2 (key 申请)

    要使用V2 的API,需要到Google APIs Console将Google Maps Android API v2服务开启(前提是你已经拥有Google帐号,并创建一个项目),见图: 然后用ke ...

  8. Android Google Map 开发步骤 地图展示空白问题

    年初时候开发了一版Google Map 地图展示店铺地址并标注点击详情,当初完整的上线Google Play 之后就没有关注过. 最近开发都有点忘记了重新梳理了一次后使用原版代码.新应用使用原版代码就 ...

  9. android 百度地图两点之间的距离计算,Android 百度地图 计算两点之间的距离

    注:Location类为自定义的实体类,里面包含latitude和longitude两个属性(Double类型) /** * 计算两点之间距离 * @param start * @param end ...

最新文章

  1. 实用的bit 位操作
  2. boost中的shared_ptr的一些理解
  3. OA系统常见的审批流程
  4. python编程狮电脑版_w3cschool编程狮PC版-编程狮电脑版下载 v3.3.10--PC6电脑版
  5. 封装类(Merry May Day to all you who are burried in work ~)---2017-05-01
  6. Vue获取DOM元素的属性值
  7. Paper and Codes Leaderboard
  8. 【自我救赎--牛客网Top101 4天刷题计划】 第三天 渐入佳境
  9. 使用busybox制作根文件系统(rootfs)
  10. 21天学通python-21天学通Python PDF 高清版
  11. linux 卸载docker 离线_Linux环境安装、卸载Docker
  12. 最简单的字符串算式计算方法
  13. interlib系统服务器,Interlib图书馆集群管理系统
  14. 超级好用的网站整站下载工具
  15. 【分享】GIS领域论坛社区
  16. R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、编写自定义三线表结构(将因子变量细粒度化重新构建三线图)
  17. 手机wifi已连接但无法访问互联网_我们的手机WiFi出现“已连接但无法上网”时咋办?...
  18. 使用OpenResty达到十万级并发超高性能Web应用(一):HelloWorld
  19. 直击|ofo测试折扣商城 押金可转换为金币消费
  20. Scala中的集合排序总结

热门文章

  1. 深入理解Java虚拟机2——内存管理机制及工具
  2. IOS创建静态库Cocoa Touch Static Library
  3. DataGrid与SQL Server 2000数据绑定
  4. Scrapy中的Spider
  5. mysql时区问题解决方案
  6. Go 用JSON加载表格数据
  7. 获取类路径的方法之一
  8. 取消冒泡的兼容性写法
  9. mvc图片上传到服务器
  10. 实训|第七天横扫Linux磁盘分区、软件安装障碍附制作软件仓库