【问题标题】:Draw route between two coordinates在两个坐标之间绘制路线
【发布时间】:2019-11-08 22:32:33
【问题描述】:

我正在使用来自 Google 的 Google Maps Directions api,我试图在 2 个坐标之间插入一条折线,我该怎么做?

我在 gradle.properties 中添加了 API 密钥,如下所示:

GOOGLE_MAPS_API_KEY = MY-API-KEY-HERE

而且我可以在我的代码中访问“LatLng”等,所以一切似乎都工作正常。

但我的问题是.. 如何在路线中的坐标之间绘制折线?我检查了其他一些示例,但似乎没有一个有效。我必须从网络上获取数据还是一切都已经设置好?

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{

private GoogleMap mMap;
MarkerOptions place1, place2;

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

    getAddressDirection();
}

public void getAddressDirection(){
    place1 = new MarkerOptions().position(new LatLng(57.6800907, 12.0031394)).title("Loc1");
    place2 = new MarkerOptions().position(new LatLng(57.9576648, 12.1188331)).title("Loc2");
}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    mMap.setMyLocationEnabled(true);

    //Adding marker between two coordinates
    mMap.addMarker(place1);
    mMap.addMarker(place2);
}

}

【问题讨论】:

    标签: java android google-maps


    【解决方案1】:

    在两个坐标之间绘制折线需要几个步骤。

    1 - 你需要点击这个网址

    https://maps.googleapis.com/maps/api/directions/jsonorigin=Toronto&destination=Montreal&key=YOUR_API_KEY
    

    2- 您需要解析响应并获取所有坐标列表并将其提供给 PolyLine。

    我建议你用你自己的 API KEY 看看这个repo

    【讨论】:

    • 通过遵循 swati 的代码,我得到了折线,但它没有跟随道路,如高速公路等。所以我真的需要使用链接吗?因为现在这条线正在从位置 1 到位置 2 画一条直线
    【解决方案2】:

    您需要向地图添加折线和多边形。

      @Override
    public void onMapReady(GoogleMap googleMap) {
        Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
                .clickable(true)
                .add(
                        new LatLng(-35.016, 143.321),
                        new LatLng(-32.491, 147.309)));
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-23.684, 133.903), 4));
    

    }

    更多详情请访问enter link description here

    【讨论】:

    • 所以你的代码确实可以画出线,但它不遵循路线(如高速公路等)我该怎么做?
    • 对于高速公路,您可以找到 latitude 和 longitude 之间的所有坐标,然后添加Polyline。
    【解决方案3】:

    我觉得你应该试试看我的代码

    @Override
    public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    
    // Add a marker in Sydney and move the camera
    mMap.setMyLocationEnabled(true);
    
    //Adding marker between two coordinates
    mMap.addMarker(place1);
    mMap.addMarker(place2);
    
    String url = getDirectionsUrl();
    new DownloadTask().execute(url);
    }
    
    private String getDirectionsUrl()
    {
        String str_origin = "origin="+57.6800907+","+12.0031394;
        String str_dest = "destination="+57.9576648+","+12.1188331;
        String sensor = "sensor=false";
        String parameters = str_origin+"&"+str_dest+"&"+sensor;
        String output = "json";
        String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
        return url;
    }
    

    DownloadTask 是我的 AsycTask,如下所示

    private class DownloadTask extends AsyncTask<String, Void, String> {
        ProgressDialog dialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MapDetailActivity.this);
            dialog.setMessage("Please wait...");
            dialog.setCancelable(false);
            dialog.show();
            ISPROGRESS = true;
        }
        @Override
        protected String doInBackground(String... url) {
            String data = "";
            try{
                data = downloadUrl(url[0]);
            }catch(Exception e){
                //Log.e("XXX","Exception while downloading "+e.toString());
            }
            return data;
        }
        @Override
        protected void onPostExecute(String result)  {
            super.onPostExecute(result);
            dialog.dismiss();
            new ParserTask().execute(result);
    
        }
    }
    
    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.e("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }
    

    ParserTask 是用于在谷歌地图上绘制路径的新异步任务

    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >
    {
        @Override
        protected List<List<HashMap<String, String>>> doInBackground(String... jsonData)
        {
            JSONObject jObject;
            List<List<HashMap<String, String>>> 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<String, String>>> result) {
            ArrayList<LatLng> points = null;
            //PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();
            String distance = "";
            String duration = "";
    
            if(result.size()<1){
                Toast.makeText(getApplicationContext(), "No Points", Toast.LENGTH_SHORT).show();
                return;
            }
            for(int i=0;i<result.size();i++){
                points = new ArrayList<LatLng>();
                //lineOptions = new PolylineOptions();
    
                List<HashMap<String, String>> path = result.get(i);
    
                for(int j=0;j<path.size();j++)
                {
                    HashMap<String,String> point = path.get(j);
    
                    if(j==0){
                        distance = (String)point.get("distance");
                        continue;
                    }else if(j==1){
                        duration = (String)point.get("duration");
                        continue;
                    }
                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);
                    points.add(position);
                }
                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points);
                lineOptions.width(5);
                lineOptions.color(Color.RED);
    
            }
            //textView_distance.setText(distance); //if you want
            //textView_time.setText(duration); //if you want
            mMap.addPolyline(lineOptions);
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Latitude,Longitude),15f));
            ISPROGRESS = false;
        }
    }
    

    而lastone是DirectionJSONParser是readymate类

    public class DirectionsJSONParser {
    
    /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
    public List<List<HashMap<String,String>>> parse(JSONObject jObject)
    {
        List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;
        JSONObject jDistance = null;
        JSONObject jDuration = null;
    
        try {
    
            jRoutes = jObject.getJSONArray("routes");
    
            /** Traversing all routes */
            for(int i=0;i<jRoutes.length();i++){
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
    
                List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();
    
                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){
    
                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));
    
                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));
    
                    /** Adding distance object to the path */
                    path.add(hmDistance);
    
                    /** Adding duration object to the path */
                    path.add(hmDuration);
    
    
                    jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
    
                    /** Traversing all steps */
                    for(int k=0;k<jSteps.length();k++){
                        String polyline = "";
                        polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);
    
                        /** Traversing all points */
                        for(int l=0;l<list.size();l++){
                            HashMap<String, String> hm = new HashMap<String, String>();
                            hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                            hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                            path.add(hm);
                        }
                    }
                }
                routes.add(path);
            }
    
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        catch (Exception e){
        }
        return routes;
    }
    
    /**
     * Method to decode polyline points
     * Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
     * */
    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;
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多