在谷歌地图v2的安卓版上突出显示指定路线

8

好的,目前我在我的应用程序中使用Google Directions API来检索两个位置之间的路线。

当我发送路线方向请求时,我会获得有关路线的许多JSON细节,包括沿途每条道路的名称、它们对应的起始和结束的经纬度坐标以及它们的polyline值。

例如:如果我发送http://maps.googleapis.com/maps/api/directions/json?origin=redfern+ave,+dublin&destination=limetree+ave,+dublin&sensor=false请求来查找两条道路之间的路线,我会收到以下JSON响应(输出一条路线)。

 {
                     "distance" : {
                        "text" : "0.2 km",
                        "value" : 203
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 18
                     },
                     "end_location" : {
                        "lat" : 53.435250,
                        "lng" : -6.132140000000001
                     },
                     "html_instructions" : "Head \u003cb\u003eeast\u003c/b\u003e on \u003cb\u003eRedfern Ave.\u003c/b\u003e toward \u003cb\u003eMartello Court\u003c/b\u003e",
                     **"polyline" : {
                        "points" : "woceIvgmd@O}DOkDQqF"**
                     },

到目前为止,我的应用程序解析了这些信息,并简单地以列表视图列出了道路和方向,如下所示:

enter image description here

我想在地图上突出显示从A到B的整条路线,但是我在新的Google Maps API v2上找不到有用的在线信息。我看到polyline被用于绘制谷歌地图v2上的线条,而不是覆盖物,然而据我所知,它们只能画直线,这对我来说是无用的。是否有任何方法可以使用我掌握的信息(道路名称、起点和终点的经纬度坐标、折线点)来突出显示路线?感谢任何帮助。 此外,我发现响应中有一个'polyline'值,可能很有用,但我不知道如何解析或使用这个信息。有人知道如何理解这个值以绘制折线吗?
**"polyline" : {
             "points" : "woceIvgmd@O}DOkDQqF"**

编辑:我的解决方案代码在下面的答案中提供。

3个回答

36

经过多次尝试,我终于让它成功运行了!现在它可以完全高亮显示从A到B的指定路线在地图上(如下面的截图所示)。我还放置了我的代码,以备将来需要的人使用。

enter image description here

public class PolyMap extends Activity {
        ProgressDialog pDialog;
        GoogleMap map;
        List<LatLng> polyz;
        JSONArray array;
        static final LatLng DUBLIN = new LatLng(53.344103999999990000,
                -6.267493699999932000);

        @SuppressLint("NewApi")
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.map_layout);
            map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(DUBLIN, 15));
            map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
            new GetDirection().execute();
        }

        class GetDirection extends AsyncTask<String, String, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(PolyMap.this);
                pDialog.setMessage("Loading route. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
            }

            protected String doInBackground(String... args) {
                Intent i = getIntent();
                String startLocation = i.getStringExtra("startLoc");
                String endLocation = i.getStringExtra("endLoc");
                            startLocation = startLocation.replace(" ", "+");
                    endLocation = endLocation.replace(" ", "+");;
                String stringUrl = "http://maps.googleapis.com/maps/api/directions/json?origin=" + startLocation + ",+dublin&destination=" + endLocation + ",+dublin&sensor=false";
                StringBuilder response = new StringBuilder();
                try {
                    URL url = new URL(stringUrl);
                    HttpURLConnection httpconn = (HttpURLConnection) url
                            .openConnection();
                    if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        BufferedReader input = new BufferedReader(
                                new InputStreamReader(httpconn.getInputStream()),
                                8192);
                        String strLine = null;

                        while ((strLine = input.readLine()) != null) {
                            response.append(strLine);
                        }
                        input.close();
                    }

                    String jsonOutput = response.toString();

                    JSONObject jsonObject = new JSONObject(jsonOutput);

                    // routesArray contains ALL routes
                    JSONArray routesArray = jsonObject.getJSONArray("routes");
                    // Grab the first route
                    JSONObject route = routesArray.getJSONObject(0);

                    JSONObject poly = route.getJSONObject("overview_polyline");
                    String polyline = poly.getString("points");
                    polyz = decodePoly(polyline);

                } catch (Exception e) {

                }

                return null;

            }

            protected void onPostExecute(String file_url) {

                for (int i = 0; i < polyz.size() - 1; i++) {
                    LatLng src = polyz.get(i);
                    LatLng dest = polyz.get(i + 1);
                    Polyline line = map.addPolyline(new PolylineOptions()
                            .add(new LatLng(src.latitude, src.longitude),
                                    new LatLng(dest.latitude,                dest.longitude))
                            .width(2).color(Color.RED).geodesic(true));

                }
                pDialog.dismiss();

            }
        }

        /* Method to decode polyline 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;
        }
    }

1
这对我帮助很大,谢谢。如果您想重复使用同一地图,则必须考虑将Polyline线保存在数组中,这样您就可以从该地图中删除这些线。 - José Castro
@DanCoghlan 你好,我是Android的新手,我不知道我需要为这个字符串startLocation = i.getStringExtra(“startLoc”)提供什么。 String endLocation = i.getStringExtra(“endLoc”); - SathishKumar
1
纬度和经度坐标,用点或逗号分隔? - Gilberto Ibarra
运行良好。感谢提供信息。 - T-D
@kabuto178 作为帮助的参考,请遵循文档:您希望计算方向的地址、地点ID或文本纬度/经度值可以用作起点。这是一个链接 https://developers.google.com/maps/documentation/directions/intro - T-D
显示剩余5条评论

3
使用Android地图API 2,确实需要使用Polyline类在地图上绘制路线(至少这是最简单的方法:))。你需要做的是提供沿途路线的点列表。
至于突出显示活动路线-在Polyline类中有一个方便的接口setColor,因此您可以将任何颜色设置为活动路线(包括alpha通道)。
Polyline line1 = map.addPolyline(new PolylineOptions()
 .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
 .width(5)
 .color(0xFFFF0000)); //non transparent red

Polyline line2 = map.addPolyline(new PolylineOptions()
 .add(new LatLng(51.5, -0.1), new LatLng(40.8, -74.2))
 .width(5)
 .color(0x7F0000FF)); //semi-transparent blue

请注意您可以随时更改折线的颜色(例如在用户单击或其他情况下)。
至于来自Google的JSON响应-路线点已经被编码,因此您可以参考this question了解如何解码。

如果你的路径有10个点,折线将画出10(实际上是9)条连接在一起的直线。你的路径有多少个点,这些点的实际坐标是什么 - 这些信息被编码到“points”字段中。 - Pavel Dudka

2

有一个简单的解决方案

添加一个库

compile 'com.google.maps.android:android-maps-utils:0.4+'

参考自 https://developers.google.com/maps/documentation/android-api/utility/setup

//Getting the points String from response of NavigationAPI call
String polyz=routeSteps.get(0).getOverview_polyline().getPoints();
//Decoding the LatLng Points using PolyUtil Class used from above Library
List<LatLng> points=PolyUtil.decode(polyz);
polyline.addAll(points);
googleMap.addPolyline(polyline);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接