How to draw a route using Google Maps? [closed]

1

I have a screen where Google Maps is located and I want it to take the user's current position and automatically route to the geolocation point that I'm going to set "Fixed" in the code. How to do?

    
asked by anonymous 14.10.2016 / 23:38

1 answer

4

I do not understand exactly what you need, but I'll try to respond.

Option 1 - If you have a GPS control and want to show on the map the route the user made from point A to point B, you only have to pick up each LatLng (latitude / longitude), add it to a List, and use Polylines , you can mount the path on the map, the more points (latitude / longitude) you have, the better, because if you only have 2 a straight line will appear connecting the 2 points.

List<LatLng> decodedPath = null;
decodedPath.add(new LatLng(0,0)); // latitude e longitude
decodedPath.add(new LatLng(1,1)); // latitude e longitude
decodedPath.add(new LatLng(2,2)); // latitude e longitude
map.addPolyline(new PolylineOptions().addAll(decodedPath).color(Color.GRAY));

Option 2 - If you only have the current location of your GPS, and the source / destination location, but you do not have the entire route that the user did in the meantime, you need to use the Google API to do so the route, and only then can you show this information on the map. I'll put an example that is working for me.

With the map ready, add the two lines below to start the API call and fill in the map path

String urlTopass = makeURL(latLngOld.latitude, latLngOld.longitude, latLng.latitude, latLng.longitude); // lat origem, lon origem, lat destino, lon destino

new connectAsyncTask(urlTopass).execute();

Get the link so that the app can use the google API

public String makeURL(double sourcelat, double sourcelog, double destlat, double destlog) {
    StringBuilder urlString = new StringBuilder();
    urlString.append("http://maps.googleapis.com/maps/api/directions/json");
    urlString.append("?origin=");// from
    urlString.append(Double.toString(sourcelat));
    urlString.append(",");
    urlString.append(Double.toString(sourcelog));
    urlString.append("&destination=");// to
    urlString.append(Double.toString(destlat));
    urlString.append(",");
    urlString.append(Double.toString(destlog));
    urlString.append("&sensor=false&mode=driving&alternatives=true");
    return urlString.toString();
}

Start the API call, here it will take all the necessary points to go from point A to point B

private class connectAsyncTask extends AsyncTask<Void, Void, String> {
    String url;

    connectAsyncTask(String urlPass) {
        url = urlPass;
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(Void... params) {
        JSONParser jParser = new JSONParser();
        String json = jParser.getJSONFromUrl(url);
        return json;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result != null) {
            drawPath(result);
        }
    }
}

public class JSONParser {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";

    // constructor
    public JSONParser() {
    }

    public String getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            org.apache.http.HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            //Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        return json;

    }
}

Refresh the map with the path passed by the Google API

public void drawPath(String result) {
    if (line != null) {
        //myMap.clear();
    }

    try {
        // Tranform the string into a json object
        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
        String encodedString = overviewPolylines.getString("points");
        List<LatLng> list = decodePoly(encodedString);

        for (int z = 0; z < list.size() - 1; z++) {
            LatLng src = list.get(z);
            LatLng dest = list.get(z + 1);
            line = myMap.addPolyline(new PolylineOptions()
                    .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
                    .width(5).color(Color.BLUE).geodesic(true));
        }

    } catch (Exception e) {
        e.printStackTrace();

    } 
}

Decode the API return for LatLng points so the app can show on the map

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;
}
    
15.10.2016 / 03:14