【问题标题】:How to draw route directions from a marker to another one ? Googlemaps v2 Android如何绘制从标记到另一个标记的路线方向?谷歌地图 v2 安卓
【发布时间】:2014-04-27 10:24:14
【问题描述】:

这是我的代码:

    public class MyGoogleMapActivity extends FragmentActivity {


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.googlemap);

            GoogleMap map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

            map.setMyLocationEnabled(true);

            LatLng Paris= new LatLng(64.711696, 12.170481);
            map.addMarker(new MarkerOptions().title("LolluSaba").position(Paris));
            LatLng Cinema= new LatLng(34.711696, 2.170481);
            map.addMarker(new MarkerOptions().title("Pseudo").position(Cinema));
       }
    }

我喜欢画一条从巴黎到电影院的路线。怎样才能很简单呢?

【问题讨论】:

    标签: android google-maps google-maps-api-3 google-maps-markers android-drawable


    【解决方案1】:

    假设你有你要绘制的两点的坐标,你可以通过以下方法从google获取路线:

    class GetDirection extends AsyncTask<String, String, String> {
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MapaAnunciante.this);
            dialog.setMessage("Drawing the route, please wait!");
            dialog.setIndeterminate(false);
            dialog.setCancelable(false);
            dialog.show();
        }
    
        protected String doInBackground(String... args) {
            String stringUrl = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin+ "&destination=" + destination+ "&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");
                pontos = decodePoly(polyline);
    
            } catch (Exception e) {
    
            }
    
            return null;
    
        }
    
        protected void onPostExecute(String file_url) {
            for (int i = 0; i < pontos.size() - 1; i++) {
                LatLng src = pontos.get(i);
                LatLng dest = pontos.get(i + 1);
                try{
                    //here is where it will draw the polyline in your map
                    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));
                }catch(NullPointerException e){
                    Log.e("Error", "NullPointerException onPostExecute: " + e.toString());
                }catch (Exception e2) {
                    Log.e("Error", "Exception onPostExecute: " + e2.toString());
                }
    
            }
            dialog.dismiss();
    
        }
    }
    
    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;
    }
    

    其中origindestination是两个包含点的纬度和经度的字符串,格式如“-1.0,2.0”:

     String origin = "64.711696,12.170481";
     String destination = "34.711696,2.170481";
    

    要执行它,只需调用new GetDirection().execute();

    希望对你有帮助!

    【讨论】:

    • 所以我必须创建另一个类,即 Get Direction ?我可以把这个加入 MyGoogleMapActivity 吗?
    • 是的,你可以在 MyGoogleMapActivity 中创建它,我也在我的 Activity 中创建了 GetDirection!
    • 我有一些错误:对话框无法解析为变量,MapaAnunciante 无法解析为类型,pontos 无法解析为变量,并且 GetDirection 类型未定义方法 decodePoly(String)。我该怎么办?
    • oh sry... MapaAnunciante 是你的 MyGoogleMapActivity,pontos 被定义为私有 List pontos;,方法 decodePoly 就在类下面,它应该可以工作
    • 只是声明了一个私有的ProgressDialog对话框;所以在绘制路线的时候会有一个对话框
    【解决方案2】:

    因为你有两点,所以通过谷歌 json 发送它,它提供了绘制路线 两点之间。请参阅此示例。

    Route direction between two location

    【讨论】:

      【解决方案3】:

      您需要将 Directions API 与 Android Maps util Lib 结合使用

      1. 从 Directions Api 获取 Encoded Polyline 字符串。
      2. 使用 Maps Util Lib 将编码字符串解码为 lat/lng 列表 (https://developers.google.com/maps/documentation/android/utility/#poly-encoding)
      3. 使用纬度/经度在地图上绘制折线!

      【讨论】:

        【解决方案4】:

        首先是你需要的 LatLng 列表

        List&lt;LatLng&gt; ls_pos=new ArrayList&lt;&gt;();

        在 OnMapReady 之后

        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                    @Override
                    public boolean onMarkerClick(final Marker marker) {
           if (ls_pos.size() >= 2) {
        
         mMap.addPolyline(newPolylineOptions().addAll(ls_pos).width(10).color(Color.RED).visible(true).clickable(true));
        
             ls_pos.clear
        

        这对我有用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-12
          • 1970-01-01
          • 1970-01-01
          • 2018-01-19
          • 2021-02-15
          • 2018-02-11
          相关资源
          最近更新 更多