Нарисуйте маршруты между несколькими точками на карте

Я новичок в Android. Я хочу провести маршруты между несколькими маркерами. Я получаю широту, долготу и дату и время с сервера. Теперь я хочу показать маршрут между точками. Я сохранил их в arraylist. Вот как я получаю очки в асинхронной задаче doInBackground ().

  newLatt= new ArrayList<String>();
  newLongg= new ArrayList<String>();
  newdatTime= new ArrayList<String>();

  JSONArray arr = new JSONArray(strServerResponse);
  for (int i = 0; i < arr.length(); i++) {
        JSONObject jsonObj1 = arr.getJSONObject(i);
        String status = jsonObj1.optString("status");
        if (status!="false"){
          Pojo pojo = new Pojo();
          String latitude = jsonObj1.optString("Latitude");
          String longitude = jsonObj1.optString("Longitude");
          String date_time = jsonObj1.optString("date_time");
          newLatt.add(latitude);
          newLongg.add(longitude);
          newdatTime.add(date_time);
       }else {
              Handler handler = new Handler(Looper.getMainLooper());
              handler.post(new Runnable() {
              @Override
              public void run() {
                   AlertDialog alertDialog = new AlertDialog.Builder(
                   MapActivity.this).create();
                   alertDialog.setMessage("Locations Not Available");
                   alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int which) {
                   }
                   });
                    alertDialog.show();
                  }
               }
       );
     }

а в методе postExecute () я показываю маркеры

        SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        map = supportMapFragment.getMap();
        map.setMyLocationEnabled(true);
        if (newLatt.size()>0){
            for (int i = 0; i < newLatt.size(); i++) {
                Double lati = Double.parseDouble(newLatt.get(i));
                Double longi = Double.parseDouble(newLongg.get(i));
                String dattme = newdatTime.get(i);
                dest = new LatLng(lati, longi);
                if (map != null) {
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(dest);
                    map.moveCamera(CameraUpdateFactory.newLatLng(dest));
                    map.animateCamera(CameraUpdateFactory.zoomTo(15));

                    markerOptions.icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_RED));
                    markerOptions.title("" + dattme);
                    map.addMarker(markerOptions);
                    map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker) {
                            marker.showInfoWindow();
                            return false;
                        }
                    });

ОБНОВЛЕНИЕ

 PolylineOptions rectOptions = new PolylineOptions();
        //this is the color of route
        rectOptions.color(Color.argb(255, 85, 166, 27));
        LatLng startLatLng = null;
        LatLng endLatLng = null;
        SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        map = supportMapFragment.getMap();
        map.setMyLocationEnabled(true);
        if (newLatt.size()>0){
            for (int i = 0; i < newLatt.size(); i++) {
                Double lati = Double.parseDouble(newLatt.get(i));
                Double longi = Double.parseDouble(newLongg.get(i));
                String dattme = newdatTime.get(i);
                dest = new LatLng(lati, longi);
                if (map != null) {
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(dest);
                    map.moveCamera(CameraUpdateFactory.newLatLng(dest));
                    map.animateCamera(CameraUpdateFactory.zoomTo(15));

                    markerOptions.icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_RED));
                    markerOptions.title("" + dattme);
                    map.addMarker(markerOptions);
                    map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker) {
                            marker.showInfoWindow();
                            return false;
                        }
                    });

                        LatLng latlng = new LatLng(lati,
                                longi);
                        if (i == 0) {
                            startLatLng = latlng;
                        }
                        if (i == newLatt.size() - 1) {
                            endLatLng = latlng;
                        }
                        rectOptions.add(latlng);
                    String url = getDirectionsUrl(startLatLng, endLatLng);
                    DownloadTask downloadTask = new DownloadTask();
                    downloadTask.execute(url);
                }

            }
            map.addPolyline(rectOptions);

получить направления:

    private String getDirectionsUrl(LatLng origin, LatLng dest) {
    // Origin of route
    String str_origin = "origin=" + origin.latitude + ","
            + origin.longitude;

    // Destination of route
    String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

    // Sensor enabled
    String sensor = "sensor=false";

    // Building the parameters to the web service
    String parameters = str_origin + "&" + str_dest + "&" + sensor;

    // Output format
    String output = "json";

    // Building the url to the web service
    String url = "https://maps.googleapis.com/maps/api/directions/"
            + output + "?" + parameters;

    return url;
}

person Community    schedule 08.10.2015    source источник


Ответы (2)


В свой postExecute добавьте следующий код, чтобы добавить плоские линии на карту.

                PolylineOptions rectOptions = new PolylineOptions();
                //this is the color of route
                rectOptions.color(Color.argb(255, 85, 166, 27));

                LatLng startLatLng = null;
                LatLng endLatLng = null;
                for (int i = 0; i < newLatt.size(); i++) {
                Double lati = Double.parseDouble(newLatt.get(i));
                Double longi = Double.parseDouble(newLongg.get(i));
                    LatLng latlng = new LatLng(lati,
                            longi);
                    if (i == 0) {
                        startLatLng = latlng;
                    }
                    if (i == jArr.length() - 1) {
                        endLatLng = latlng;
                    }
                    rectOptions.add(latlng);
                }
                map.addPolyline(rectOptions);

Удачного кодирования ...

person A Raj    schedule 08.10.2015
comment
Зарегистрируйте размер newLatt. У вас прямая линия, потому что у вас, вероятно, только две широты. - person A Raj; 08.10.2015
comment
извините, это была моя часть кода. Для u замените jArr.length () на newLatt.size () - person A Raj; 08.10.2015
comment
Я то должен нормально работать. если ты получил то, что ожидал. Пожалуйста проголосуйте за - person A Raj; 08.10.2015
comment
Я получаю исключение нулевого указателя в строке str_dest = destination = + dest.latitude +, + dest.longitude; в getDirectionsurl - person ; 08.10.2015
comment
Позвольте нам продолжить это обсуждение в чате. - person A Raj; 08.10.2015

person    schedule
comment
Да, я знаю это. но у меня есть широта и долгота в arraylist, как получить к ним доступ, чтобы показать маршрут ?? - person ; 08.10.2015
comment
в вашем списке есть хеш-карта? - person USKMobility; 08.10.2015