【问题标题】:How can I get array of available routing LatLng between Source LatLng and destination LatLng?如何获取源 LatLng 和目标 LatLng 之间的可用路由 LatLng 数组?
【发布时间】:2017-08-04 08:22:38
【问题描述】:

我想根据我的 Android 应用程序中的可用路线,在源和目的地之间的 Google 地图中添加一些检查点(标记)。

【问题讨论】:

  • 你用谷歌搜索了吗?
  • @RahulKhurana 我做了,但没有得到我想要的东西
  • 请考虑接受答案或发布您自己的解决方案。它可能对其他有相同问题的人有所帮助。谢谢。

标签: android google-maps android-layout android-maps-v2


【解决方案1】:

查看此 Google 地图教程HERE

在第 4 步中,您解析一个包含不同路由的 JSON。从每条路线中,您可以获得具有 Lat 和 Lng 值的点。

【讨论】:

    【解决方案2】:
    public class PathToDestination {
    
        private GoogleMap mMap;
        private Context context;
        private static final String API_KEY = "your key";
    
        private String pathColor = "#05b1fb";//default blue color
        private int pathWidth = 5;//default is 5
        private Polyline line;
        private PolylineOptions polylineOptions;
    
        public PathToDestination(Context context, GoogleMap mMap) {
            this.context = context;
            this.mMap = mMap;
        }
    
        public void setPathColor(String pathColor) {
            this.pathColor = pathColor;
        }
    
        public void setPathWidth(int pathWidth) {
            this.pathWidth = pathWidth;
        }
    
        public void drawPathBetween(@MapManager.PathMode int mode, double sourcelat, double sourcelog, double destlat, double destlog) {
            drawPathBetween(mode, sourcelat, sourcelog, destlat, destlog, null);
        }
    
        public void drawPathBetween(@MapManager.PathMode int mode, double sourcelat, double sourcelog, double destlat, double destlog, MapModel[] waypoints) {
            String urlStr = makeURL(mode, sourcelat, sourcelog, destlat, destlog, waypoints);
            new ConnectAsyncTask(urlStr).execute();
        }
    
        /*private String makeURL(double sourcelat, double sourcelog, double destlat, double destlog) {
            return makeURL(sourcelat, sourcelog, destlat, destlog, );
        }*/
    
        private String makeURL(@MapManager.PathMode int mode, double sourcelat, double sourcelog, double destlat, double destlog, MapModel... waypoints) {
            StringBuilder urlString = new StringBuilder();
            urlString.append("https://maps.googleapis.com/maps/api/directions/json");
            urlString.append("?origin=");// from
            urlString.append(Double.toString(sourcelat));
            urlString.append(",");
            urlString.append(Double.toString(sourcelog));
            if (waypoints != null && waypoints.length > 0) {
                urlString.append("&waypoints=");// waypoints
                for (int i = 0; i < waypoints.length; i++) {
                    MapModel coordinate = waypoints[i];
                    urlString.append(coordinate.getLatitude());
                    urlString.append(",");
                    urlString.append(coordinate.getLongitude());
                    if (i < waypoints.length - 1) {
                        urlString.append("|");
                    }
                }
            }
            urlString.append("&destination=");// to
            urlString.append(Double.toString(destlat));
            urlString.append(",");
            urlString.append(Double.toString(destlog));
            urlString.append("&sensor=false");
            urlString.append("&mode=" + mode);
            urlString.append("&alternatives=true");
            urlString.append("&key=" + API_KEY);
            return urlString.toString();
        }
    
        private void drawPath(String result) {
    
            try {
                //Tranform the string into a json object
                final JSONObject json = new JSONObject(result);
                JSONArray routeArray = json.getJSONArray("routes");
                JSONObject routes = routeArray.getJSONObject(0);
                JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
                String encodedString = overviewPolylines.getString("points");
                List<LatLng> list = null;
    
                if (polylineOptions == null) {
                    polylineOptions = new PolylineOptions()
                            .width(pathWidth)
                            .color(Color.parseColor(pathColor)) //Google maps blue color
                            .geodesic(true);
                }
    
                list = decodePoly(encodedString);
                polylineOptions.addAll(list);
    
                if (line == null) {
                    line = mMap.addPolyline(polylineOptions);
                }
    
                line.setPoints(list);
               /*
               for(int z = 0; z<list.size()-1;z++){
                    LatLng src= list.get(z);
                    LatLng dest= list.get(z+1);
                    Polyline line = mMap.addPolyline(new PolylineOptions()
                    .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude,   dest.longitude))
                    .width(2)
                    .color(Color.BLUE).geodesic(true));
                }
               */
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    
        public void drawPathFromEncodedPolyline(String encodedPolyline) {
    
    //        try {
            //Tranform the string into a json object
    //            final JSONObject json = new JSONObject(result);
    //            JSONArray routeArray = json.getJSONArray("routes");
    //            JSONObject routes = routeArray.getJSONObject(0);
    //            JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
    //            String encodedString = overviewPolylines.getString("points");
            List<LatLng> list = decodePoly(encodedPolyline);
            Polyline line = mMap.addPolyline(new PolylineOptions()
                    .addAll(list)
                    .width(5)
                    .color(Color.parseColor("#05b1fb"))//Google maps blue color
                    .geodesic(true)
            );
               /*
               for(int z = 0; z<list.size()-1;z++){
                    LatLng src= list.get(z);
                    LatLng dest= list.get(z+1);
                    Polyline line = mMap.addPolyline(new PolylineOptions()
                    .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude,   dest.longitude))
                    .width(2)
                    .color(Color.BLUE).geodesic(true));
                }
               */
    //        } catch (JSONException e) {
    //            e.printStackTrace();
    //        }
        }
    
        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;
        }
    
    
        private class ConnectAsyncTask extends AsyncTask<Void, Void, String> {
            private ProgressDialog progressDialog;
            String url;
    
            ConnectAsyncTask(String urlPass) {
                url = urlPass;
            }
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 &&
                        !((Activity) context).isDestroyed()) ||
                        !((Activity) context).isFinishing()) {
                    progressDialog = new ProgressDialog(context);
    //                progressDialog.setMessage("Fetching route, Please wait...");
    //                progressDialog.setIndeterminate(true);
    //                progressDialog.show();
                }
            }
    
            @Override
            protected String doInBackground(Void... params) {
                HttpURLConnection conn = null;
                StringBuilder jsonResults = new StringBuilder();
                try {
                    URL url = new URL(this.url);
                    conn = (HttpURLConnection) url.openConnection();
                    InputStreamReader in = new InputStreamReader(conn.getInputStream());
    
                    // Load the results into a StringBuilder
                    int read;
                    char[] buff = new char[1024];
                    while ((read = in.read(buff)) != -1) {
                        jsonResults.append(buff, 0, read);
                    }
                } catch (MalformedURLException e) {
                    return jsonResults.toString();
                } catch (IOException e) {
                    return jsonResults.toString();
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
    
                return jsonResults.toString();
            }
    
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
    
                if (progressDialog != null) {
                    progressDialog.hide();
                }
    
                if (result != null) {
                    drawPath(result);
                }
            }
        }
    
        public void clearRoute() {
            if (line != null) {
                line.remove();
            }
            line = null;
            polylineOptions = null;
        }
    
    }
    

    这里 MapModel 是一个接口

    public interface MapModel {
        double getLatitude();
        double getLongitude();
    }
    

    如果你想要 LatLng 列表,你可以很容易地从

    drawPathFromEncodedPolyline(String encodedPolyline) 方法。

    您可以查看here 以了解其他地图功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多