Android Google Map –两点之间的绘图路线

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 google maps drawing route between two points

如果您使用的是最新的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();

    @Override
    protected 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);
    }

    @Override
    public 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() {
            @Override
            public void onMapClick(LatLng latLng) {

                if (markerPoints.size() > 1) {
                    markerPoints.clear();
                    mMap.clear();
                }

                // Adding new item to the ArrayList
                markerPoints.add(latLng);

                // Creating MarkerOptions
                MarkerOptions options = new MarkerOptions();

                // Setting the position of the marker
                options.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 V2
                mMap.addMarker(options);

                // Checks, whether start and end locations are captured
                if (markerPoints.size() >= 2) {
                    LatLng origin = (LatLng) markerPoints.get(0);
                    LatLng dest = (LatLng) markerPoints.get(1);

                    // Getting URL to the Google Directions API
                    String url = getDirectionsUrl(origin, dest);

                    DownloadTask downloadTask = new DownloadTask();

                    // Start downloading json data from Google Directions API
                    downloadTask.execute(url);
                }

            }
        });

    }

    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);

        }
    }

    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap>>> {

        // Parsing the data in non-ui thread
        @Override
        protected 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;
        }

        @Override
        protected 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 route
            mMap.addPolyline(lineOptions);
        }
    }

    private String getDirectionsUrl(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";
        String mode = "mode=driving";

        // Building the parameters to the web service
        String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;

        // Output format
        String output = "json";

        // Building the url to the web service
        String 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密钥。

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值