Drawing a route between 2 locations Google Maps API Android V2

10,825

Solution 1

Sorry for the long wait.. i have fixed it a while ago but i hadn't put my solution on here yet.

It was basically a typo...

In my Json decoder i use 2 Do while statements with

while (b >= 0x20);

In the second Do While statement i forgot the "=". Therefore it wasn't rendering correctly...

thanks

Solution 2

I believe that you are creating your LatLng objects from overview_polyline. This, according to Google documentation "contains an object holding an array of encoded points that represent an approximate (smoothed) path of the resulting directions.".

I'm pretty sure that you can get a more detailed route building your LatLng object based on legs[] and steps[] data as the official documentation states that A step is the most atomic unit of a direction's route, containing a single step describing a specific, single instruction on the journey.

Take a look at:

https://developers.google.com/maps/documentation/directions/#Routes

Share:
10,825
Michael
Author by

Michael

Updated on July 27, 2022

Comments

  • Michael
    Michael almost 2 years

    I was playing around with the Google Maps API V2 on android. Trying to get a path between 2 locations and doing this with the JSON Parsing.

    I am getting a route. and the route starts out how it should be. but then at one point it goes the wrong way.

    My end destination ends up wrong. And with some other locations my app just gets terminated.

    This is what i have done

    Here is my makeURL method

    public String makeUrl(){
        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.googleapis.com/maps/api/directions/json");
        urlString.append("?origin="); //start positie
        urlString.append(Double.toString(source.latitude));
        urlString.append(",");
        urlString.append(Double.toString(source.longitude));
        urlString.append("&destination="); //eind positie
        urlString.append(Double.toString(dest.latitude));
        urlString.append(",");
        urlString.append(Double.toString(dest.longitude));
        urlString.append("&sensor=false&mode=driving");
    
        return urlString.toString();
    }
    

    my JSON parser

    public class JSONParser {
    
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    
    public JSONParser() {
        // TODO Auto-generated constructor stub
    }
    
    public String getJSONFromURL(String url){
    
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
    
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
    
            is = httpEntity.getContent();
        } catch(UnsupportedEncodingException e){
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            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");
                //Log.e("test: ", sb.toString());
            }
    
            json = sb.toString();
            is.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.e("buffer error", "Error converting result " + e.toString());
        }
    
        return json;
    }
    

    I draw my Path with this method

    public void drawPath(String result){
        try{
            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");
            Log.d("test: ", encodedString);
            List<LatLng> list = decodePoly(encodedString);
    
            LatLng last = null;
            for (int i = 0; i < list.size()-1; i++) {
                LatLng src = list.get(i);
                LatLng dest = list.get(i+1);
                last = dest;
                Log.d("Last latLng:", last.latitude + ", " + last.longitude );
                Polyline line = googleMap.addPolyline(new PolylineOptions().add( 
                        new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
                        .width(2)
                        .color(Color.BLUE));
            }
    
            Log.d("Last latLng:", last.latitude + ", " + last.longitude );
        }catch (JSONException e){
            e.printStackTrace();
        }
    }
    

    And I decode my JSON with

    private List<LatLng> decodePoly(String encoded){
    
        List<LatLng> poly = new ArrayList<LatLng>();
        int index = 0;
        int length = encoded.length();
        int latitude = 0;
        int longitude = 0;
    
        while(index < length){
            int b;
            int shift = 0;
            int result = 0;
    
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
    
            int destLat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            latitude += destLat;
    
            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b > 0x20);
    
            int destLong = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            longitude += destLong;
    
            poly.add(new LatLng((latitude / 1E5),(longitude / 1E5) ));
        }
        return poly;
    }
    

    And then coded with an AsyncTask

    Thanks in advance.