How to chart a route using Google Maps?

Asked

Viewed 4,355 times

1

I have a screen where Google Maps is and I want you to take the current position of the user and route automatically to the geolocation point that I will leave set "Fixed" in the code. How to do?

1 answer

4

I don’t understand exactly what you need, but I’ll try to answer.

Option 1 - If you have a GPS control and want to show on the map the route that the user has made from point A to point B, just take each Latlng (latitude/longitude), add in a List, and using Polylines, you can mount the path on the map, the more points (latitude/longitude) you have, better, pq if you only have 2 will appear a straight line 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 his current GPS location, and the source/destination location, but you don’t have the entire route the user has made in the meantime, you need to use the Google API to get him to do the route, and only then can you show this information on the map. I’ll put an example that’s working for me.

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

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

new connectAsyncTask(urlTopass).execute();

Grab the link so 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 pick up all the points needed 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;

    }
}

Updates the map with the path passed through 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();

    } 
}

Decodes the API return to 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;
}
  • Excuse me for my ignorance...

  • I’m sorry for my ignorance... but I was confused in your answer... So, I defined the Point in a mall in Sao Paulo, let’s assume that the user is in Rio de Janeiro, I want to automatically appear a route from the place where the user is to the fixed point where I defined that in the case is the Shopping.

  • Use the second answer, which uses the Google API, calling the function "makeURL" and the "connectAsyncTask", you just need to pass the correct latitude and longitude in the makeURL call, are 4 parameters latitude/longitude of point A and latitude/longitude of point B

Browser other questions tagged

You are not signed in. Login or sign up in order to post.