标记之间的谷歌地图API和自定义路线 [英] Google Maps API and custom routes between Markers

查看:233
本文介绍了标记之间的谷歌地图API和自定义路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个自定义路线的Andr​​oid应用程序,我不知道我应该使用哪一种API,如果它与Java兼容。

I'd like to make a custom route for an android app, I'm not sure which API should I use and if it is compatible with Java.

据我知道我需要使用的航点,使路由(我不需要知道两点之间的距离,只是为了让一个路线)。

As far as I know I need to use waypoints to make a route (I don't need to know the distance between the two points, just to make a route).

我们的目标是选择在地图上的一侧从菜单中的选项,并显示两个标记之间的自定义的途径之一。

The objective is to choose an option from a menu on the side of the map and show one of the custom routes between two Markers.

推荐答案

您可以使用的为Android 谷歌地图API V2和谷歌地图路线Web服务API

You can do this using the Google Maps API v2 for Android, and the Google Maps Directions webservice API

有关开始使用谷歌地图API,还有很多其他很好的答案已经是。 见这里一张简单的地图活动的一个完整的工作示例。请注意,您还需要得到建立与项目合作API密钥。

For getting started with the Google Maps API, there are plenty of other good answers already. See here for a complete working example of a simple map Activity. Note that you'll also need to get an API key set up to work with your project.

作为使用谷歌地图路线Web服务API,你应该先阅读文档。您可以使用一个API密钥,使您的开发人员控制台中的API,但它仍然工程目前还没有使用API​​密钥。

As for using the Google Maps Directions webservice API, you should first read the documentation. You can use an API key and enable the API in your developer console, but it still works currently without using an API key.

下面是基本的code你需要才能使用谷歌地图API绘制两点之间的折线,注意,从API返回的点都设有codeD在基带64 codeD的字符串必须去codeD。

Here is the basic code you'll need in order to use the Google Maps API to draw a Polyline between two points, note that the points returned from the API are encoded in a base 64 encoded String that needs to be decoded.

首先,这里是AsyncTask的,你应该给两个LatLng点时调用它。

First, here is the AsyncTask, that you should give two LatLng points to when calling it.

您会调用AsyncTask的两个LatLng对象,例如两个标记之间:

You would call the AsyncTask with two LatLng objects, for example between two Markers:

new GetDirectionsAsync().execute(markerOne.getPosition(), markerTwo.getPosition());

下面是AsyncTask的code:

Here is the AsyncTask code:

class GetDirectionsAsync extends AsyncTask<LatLng, Void, List<LatLng>> {

    JSONParser jsonParser;
    String DIRECTIONS_URL = "https://maps.googleapis.com/maps/api/directions/json";


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<LatLng> doInBackground(LatLng... params) {
        LatLng start = params[0];
        LatLng end = params[1];

        HashMap<String, String> points = new HashMap<>();
        points.put("origin", start.latitude + "," + start.longitude);
        points.put("destination", end.latitude + "," + end.longitude);

        jsonParser = new JSONParser();

        JSONObject obj = jsonParser.makeHttpRequest(DIRECTIONS_URL, "GET", points, true);

        if (obj == null) return null;

        try {
            List<LatLng> list = null;

            JSONArray routeArray = obj.getJSONArray("routes");
            JSONObject routes = routeArray.getJSONObject(0);
            JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
            String encodedString = overviewPolylines.getString("points");
            list = decodePoly(encodedString);

            return list;

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(List<LatLng> pointsList) {

        if (pointsList == null) return;

        if (line != null){
            line.remove();
        }

        PolylineOptions options = new PolylineOptions().width(5).color(Color.MAGENTA).geodesic(true);
        for (int i = 0; i < pointsList.size(); i++) {
            LatLng point = pointsList.get(i);
            options.add(point);
        }
        line = mMap.addPolyline(options);

    }
}

本的AsyncTask引用活动的一些成员变量,即折线和GoogleMap的,活动的定义是这样的:

The AsyncTask references some member variables of the Activity, namely the Polyline and the GoogleMap, the Activity definition would look like this:

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback{

    GoogleMap mMap;
    Polyline line;
    //.....

下面是用来脱code点去$ C $℃聚()方法:

Here's the decodePoly() method used to decode the 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;
}

下面是本例中使用的JSONParser类,注意,这是修改后的版本为Android-23,我的写了一篇博客文章

Here's the JSONParser class used in this example, note that this is a modified version updated for android-23 that I wrote a blog post about:

public class JSONParser {

    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;

    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap<String, String> params, boolean encode) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                if (encode) {
                    sbParams.append(key).append("=")
                            .append(URLEncoder.encode(params.get(key), charset));
                }
                else{
                    sbParams.append(key).append("=")
                            .append(params.get(key));
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            Log.d("JSONParser", "full GET url: " + url);

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;
            result = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

        conn.disconnect();

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON Object
        return jObj;
    }
}

绘制两个标记之间的路线的结果:

Result of drawing a route between two Markers:

在这里输入的形象描述

这篇关于标记之间的谷歌地图API和自定义路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆