0

Hi i am first time using the map in android after changing in google Map API.

Now I wants to draw the route on the map between two addresses endered by me for API v2. I don't know how to do this. I tried a lot for this. Please help me. Thanks.

My code is:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.start_trip_view);
    try {
        ArrayList<String> location = new ArrayList<String>();
        Intent ii = getIntent();

        location2 = (ii.getStringExtra("place"));
        String location3 = (ii.getStringExtra("start"));
        gps = new GPSTracker(getApplicationContext());
        latitude = gps.getLatitude();
        longitude = gps.getLongitude();
        Balvinder = new LatLng(latitude, longitude);
        markerPoints = new ArrayList<LatLng>();

        map = ((MapFragment) getFragmentManager()
                .findFragmentById(R.id.map)).getMap();
        map.setMyLocationEnabled(true);

        //

        if (location == null || location.equals("")) {
            Toast.makeText(getBaseContext(), "No Place is entered",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        String url = "https://maps.googleapis.com/maps/api/geocode/json?";
        // for(int i=0; i<location.size();i++)
        // {
        try {
            // encoding special characters like space in the user input
            // place

            location2 = URLEncoder.encode(location2, "utf-8");
//              location3 = URLEncoder.encode(location3, "utf-8");
            String saddress = "address=" + location2;
            // String Dsaddress = "address=" + location3;

            String sensor = "sensor=false";

            // url , from where the geocoding data is fetched

            url = url + saddress + "&" + sensor;

            DownloadTask downloadTask = new DownloadTask();

            // Start downloading the geocoding places
            downloadTask.execute(url);
            }


private String downloadUrl(String... strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        for(int i=0;i<strUrl.length;i++)
        {
        URL url = new URL(strUrl[i]);


        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        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.d("Exception while downloading url", e.toString());
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }

    return data;

}

// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Integer, String> {

    String data = null;

    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(String... url) {
        try {
            for(int i=0;i<url.length;i++)
            {
            data = downloadUrl(url[i]);
        }
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(String result) {

        // Instantiating ParserTask which parses the json data from
        // Geocoding webservice
        // in a non-ui thread



        ParserTask parserTask = new ParserTask();
        parserTask.execute(result);
        }
        System.out.println("Result"+result);

    }

}

/** A class to parse the Google Places in JSON format */
class ParserTask extends
        AsyncTask<String, Integer, List<HashMap<String, String>>> {

    JSONObject jObject;

    // Invoked by execute() method of this object
    @Override
    protected List<HashMap<String, String>> doInBackground(
            String... jsonData) {

        List<HashMap<String, String>> places = null;
        GeocodeJSONParser parser = new GeocodeJSONParser();

        try {
            jObject = new JSONObject(jsonData[0]);

            /** Getting the parsed data as a an ArrayList */
            places = parser.parse(jObject);

        } catch (Exception e) {
            Log.d("Exception", e.toString());
        }
        return places;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(List<HashMap<String, String>> list) {
        PolylineOptions lineOptions = new PolylineOptions();
        ArrayList<LatLng>points=new ArrayList<LatLng>();
        // Clears all the existing markers
        map.clear();

        for (int i = 0; i < list.size(); i++) {

            // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

            // Getting a place from the places list
            HashMap<String, String> hmPlace = list.get(i);

            // Getting latitude of the place
             lat = Double.parseDouble(hmPlace.get("lat"));

            // Getting longitude of the place
             lng = Double.parseDouble(hmPlace.get("lng"));

            // Getting name
            String name = hmPlace.get("formatted_address");

            latLng = new LatLng(lat, lng);

            // Setting the position for the marker
            markerOptions.position(latLng);
            // getDirectionsUrl(Balvinder, latLng);
            // markerOptions.position(Balvinder);

                    .show();
    map.addMarker(new MarkerOptions().title("My Location").snippet(
    gps.ConvertPointToLocation(latitude, longitude,
                            StartTripView.this))
            .position(Balvinder)
            .icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.logo_sono)));
            markerPoints.add(Balvinder);
            markerPoints.add(latLng);
            //makeURL(latitude, longitude, lat, lng);
    System.out.println("Result"+makeURL(latitude, longitude, lat, lng));
            // Polyline line = map.addPolyline(new PolylineOptions()
            // .add(Balvinder, latLng)
            // .width(5)
            // .color(Color.RED).geodesic(true));




            markerOptions.title(name);
            //
            map.addMarker(markerOptions);

    if (i == 0){
          map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }

        }


}

}
Amrit
  • 2,295
  • 4
  • 25
  • 42
Balvinder Singh
  • 580
  • 6
  • 19
  • What is the problem with your code? Crash? Error message? wrong info? – Waza_Be Jul 22 '13 at 06:58
  • no crash It shows the two locations on map but I want to draw a driving route between them – Balvinder Singh Jul 22 '13 at 07:06
  • Look at this link.... http://stackoverflow.com/questions/14710744/how-to-draw-road-directions-between-two-geocodes-in-android-google-map-v2/16315944#16315944 – Dhruv Oct 02 '13 at 05:48

3 Answers3

0

Documentation: https://developers.google.com/maps/documentation/android/shapes?hl=fr#polylines

To draw the route between 2 locations, you should use a polyline:

// Instantiates a new Polyline object and adds points to define a rectangle
PolylineOptions rectOptions = new PolylineOptions()
        .add(new LatLng(37.35, -122.0))
        .add(new LatLng(37.45, -122.0))  // North of the previous point, but at the same longitude
        .add(new LatLng(37.45, -122.2))  // Same latitude, and 30km to the west
        .add(new LatLng(37.35, -122.2))  // Same longitude, and 16km to the south
        .add(new LatLng(37.35, -122.0)); // Closes the polyline.

// Get back the mutable Polyline
Polyline polyline = myMap.addPolyline(rectOptions);

In your case you won't need the last point to close the polyline.

Waza_Be
  • 39,407
  • 49
  • 186
  • 260
  • i am already used this code but it only draw straight line between two points not displaying driving directions – Balvinder Singh Jul 22 '13 at 07:41
  • It draws line between multiple points. That s what you can get to dispay driving directions. What do you expect? – Waza_Be Jul 22 '13 at 20:33
0

Check this example Driving Direction

You can use Reverse Geocoding

     Geocoder geocoder = new Geocoder(context);
     address = geocoder.getFromLocationName("your address");

get lat/lng from the address and pass that in the above example.

Srikanth Roopa
  • 1,782
  • 2
  • 13
  • 19
  • the suggested link shows the the route while touch on the map. but iam passing the addresses in the textbox and sendint to mapFragment now iam try to draw route between theese two adresses. – Balvinder Singh Jul 22 '13 at 07:24
  • yes instead of that u modify according to your needs. Once u have the lat/lng call directionsURl and pass the values. // Getting URL to the Google Directions API String url = getDirectionsUrl(origin, dest); DownloadTask downloadTask = new DownloadTask(); downloadTask.execute(url); – Srikanth Roopa Jul 22 '13 at 07:30
0

Please first check ur api response is your key is valid the use my below asynctask code

     private class DownloadTask extends AsyncTask {

    ProgressDialog asyncDialog = new ProgressDialog(NearGoogleMap.this);  




    String StatusOK="", url;

    String data = "";
    JSONArray routeArray=null,LegsArray=null,StepsArray=null;

    public DownloadTask(String url) {
        this.url=url;

    }



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        asyncDialog.setMessage("Please wait...!!!");
        //show dialog
        asyncDialog.setCancelable(false);
        asyncDialog.show();
    }

    @Override
    protected Object doInBackground(Object[] params) {


        try {
            data = downloadUrl(url);
            Log.d("Background data Task", data.toString());



            if (data.isEmpty())
            {

            }else {
                JSONObject dataJSON =new JSONObject(data);

                Log.d("data JSON", dataJSON.toString());

                StatusOK=dataJSON.getString("status");

                if (StatusOK.equals("OK"))
                {
                    Log.d("Decode JSON","StatusOK");

                    routeArray=dataJSON.getJSONArray("routes");


                    for (int i=0;i<routeArray.length();i++)
                    {
                        Log.d("Decode JSON","routes");
                        JSONObject inputJSON=routeArray.getJSONObject(i);

                        LegsArray=inputJSON.getJSONArray("legs");

                        for (int j=0;j<LegsArray.length();j++)
                        {
                            Log.d("Decode JSON","legs");
                            JSONObject inputJSONleg=LegsArray.getJSONObject(j);

                            StepsArray=inputJSONleg.getJSONArray("steps");

                            for (int k=0;k<StepsArray.length();k++)
                            {
                                Log.d("Decode JSON","steps");
                                JSONObject inputJSONstep=StepsArray.getJSONObject(k);

                                JSONObject PolylineJSON=inputJSONstep.getJSONObject("polyline");
                                Log.d("Decode JSON","polyline");

                                String getPolylineString=PolylineJSON.getString("points");
                                Log.d("Decode JSON","points");

                                List<LatLng> getPolypont=decodePolyNew(getPolylineString);
                                Log.d("Decode JSON","decodePolyNew");

                                for (int z=0;z<getPolypont.size();z++)
                                {
                                    Log.d("Decode JSON","DirectionPoint");
                                    DirectionPoint.add(new LatLng(getPolypont.get(z).latitude,getPolypont.get(z).longitude));
                                }





                            }




                        }


                    }




                }




            }



        } catch (Exception e) {
            Log.d("Background Task", e.toString());
            data="";

        }
        return null;
    }


    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        asyncDialog.dismiss();
        if (data.isEmpty())
        {
            Toast.makeText(getBaseContext(),"Something went wrong",Toast.LENGTH_SHORT).show();

        }else {
            if (DirectionPoint.size()==0)
            {

            }else {
                PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);

                for (int z = 0; z < DirectionPoint.size(); z++) {
                    LatLng point = DirectionPoint.get(z);
                    options.add(point);
                }

                mMap.addPolyline(options);











            }
        }
    }
}

// Inside onCreate() method call asynctask as follows

                if (points.size()>=2)
                {
                    // Getting URL to the Google Directions API
                    String url = getDirectionsUrl(points.get(0), points.get(1));

                    Log.d("Get URL",url);


                    DownloadTask downloadTask = new DownloadTask(url);

                    // Start downloading json data from Google Directions API
                    downloadTask.execute();

                }

            }

 // binding url getDirectionsUrl()



       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";
        String mode = "mode=driving";

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

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



     // for decode polyline use this method 

      private List decodePolyNew(String encoded) {

    List poly = new ArrayList();
    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;
}