简体   繁体   English

如何从标记到另一个标记绘制路线方向? Googlemaps v2 Android

[英]How to draw route directions from a marker to another one ? Googlemaps v2 Android

Here is my code : 这是我的代码:

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

And i like to draw a route from Paris to Cinema. 我想画一条从巴黎到电影院的路线。 How can I do it very simply ? 我怎么能这么简单地做到这一点?

Assuming that you have the coordinates of the two points you want to draw, you can get the route from google using the following methods: 假设您有要绘制的两个点的坐标,您可以使用以下方法从谷歌获取路线:

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;
}

Where origin and destination are two strings containing the lat and lng of the points, formatted like "-1.0,2.0": 其中origindestination是两个包含点的lat和lng的字符串,格式为“-1.0,2.0”:

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

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

Hope it helps! 希望能帮助到你!

As you have two points so send it through google json which provides to draw route between two points. 因为你有两个点,所以通过谷歌json发送它,提供两点之间的绘制路线。 See this example. 看这个例子。

Route direction between two location 两个位置之间的路线方向

You Need to use the Directions API in combination with the Android Maps util Lib 您需要将Directions API与Android Maps util Lib结合使用

  1. Get the Encoded Polyline String from the Directions Api. 从方向Api获取Encoded Polyline字符串。
  2. Decode the encoded string using Maps Util Lib into a list of lat/lng's ( https://developers.google.com/maps/documentation/android/utility/#poly-encoding ) 使用Maps Util Lib将编码后的字符串解码为lat / lng列表( https://developers.google.com/maps/documentation/android/utility/#poly-coding
  3. Draw the Polyline on the map using the lat/lngs! 使用lat / lngs在地图上绘制折线!

First a List of LatLng you need 首先是您需要的LatLng列表

List<LatLng> ls_pos=new ArrayList<>();

After that In OnMapReady 之后在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

That's Work for me. 这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android:如何绘制路线方向谷歌地图API V2从当前位置到目的地 - Android: How to draw route directions google maps API V2 from current location to destination 如何将ContentDesctiption添加到InfoWindow或Android GoogleMaps V2 for TalkBack中的标记 - how to add contentDesctiption to InfoWindow or marker in Android GoogleMaps V2 for TalkBack GoogleMaps V2 android获取标记图标 - GoogleMaps V2 android get marker icon 更改标记颜色Android GoogleMaps V2 - Change marker color Android GoogleMaps V2 如何使用PolylineOptions从Google Map Android V2清除路线并再次绘制一个新路线? - How to clear route from google map android v2 using PolylineOptions and draw a new one again? Android:在GoogleMap API v2中绘制从A到B的路线 - Android: draw route from A to B in GoogleMap API v2 如何在路线google maps v2 android上绘制交互式Polyline - How to draw interactive Polyline on route google maps v2 android GoogleMaps V2-显示标记的完整摘要 - GoogleMaps V2 - Show full snippet of marker 如何在android google map v2中绘制两个地理编码之间的道路方向? - How to draw road directions between two geocodes in android google map v2? Android googlemaps 聚类如何排除一个标记 - Android googlemaps clustering how to exclude one marker
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM