0
votes

I'm using Google Maps Directions api from Google and i'm trying to insert a polyline between 2 cooridnates, how can I do this?

I've added the API key inside gradle.properties like this:

GOOGLE_MAPS_API_KEY = MY-API-KEY-HERE

And I can access the "LatLng" etc inside my code, so everything seems to be working fine.

But my question is.. How can I draw a polyline between the coordinates in a route? I've checked out a few other examples but none seems to work. Do I have to get data from the web or is everything already set?

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

}

3

3 Answers

0
votes

Drawing a polyLine between two coordinates requires a couple of steps.

1 - You need a hit this url

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

2- You need to parse the response and get all the list of coordinates and feed it to PolyLine.

I suggest you to have a look at this repo with your own API KEY.

0
votes

You need to Add polylines and polygons to the map.

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

}

For more detail please visit enter link description here

0
votes

I think you should try bellow my code

@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 is my AsycTask like bellow

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 is new asynctask for draw path on google map

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

and lastone is DirectionJSONParser is readymate class

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