0

I'm working on a project that the main part is to visually demonstrates directions between two points on Google Maps, but I want this direction do pass from specific point like A and B. I fount this solution:

final Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://maps.google.com/maps?" + "saddr="+ source.latitude + "," + source.longitude+ "&daddr=" + dest.latitude+ "," + dest.longitude));
intent.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity");
startActivity(intent);

but the problem is that the route is not flexible and I have no control over it. is there any solution to my problem like changing the 'XML' source of the route?

5
  • You are using implicit intent for this, if you want clear solution then you have to use your own method to draw the line on the map woth specific location, using Polyline class you can draw this, as I have did it before and its working very fine. Commented Jul 28, 2014 at 10:05
  • I think the best solution is to control by yourself by using MapView. I can give you an example that use Google MapView v1 which has been deprecated by Google to point out the rout between two points.. But you can adapte them onto v2 easily. code.google.com/p/j2memaprouteprovider/source/browse/trunk/…
    – TeeTracker
    Commented Jul 28, 2014 at 10:09
  • @pratik how can I find streets and path? because it must be a drive-able route.
    – Branky
    Commented Jul 28, 2014 at 10:09
  • For that, I think you just needed latitude and longitude, nothing else. But one thing is you must have all the latitude and longitude which will come across in the path. Commented Jul 28, 2014 at 10:11
  • @TeeTracker I can't find any RoadProvider or Road class in api v2.
    – Branky
    Commented Jul 28, 2014 at 10:19

1 Answer 1

2

If you're obtaining the route by explicitly parsing an URL to Google try the following code, it will allow you to set the PolyLine parameters:

// URL constructor
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=walking&alternatives=true");
    return urlString.toString();
}

// draws path from result String
public void drawPath(String  result) {
    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);
            map.addPolyline(new PolylineOptions()
            .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude,   dest.longitude))
            .width(8)
            .color(Color.BLUE).geodesic(true));
        }

    } 
    catch (JSONException e) {

    }
}

// obtain route using AsyncTask
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
    private ProgressDialog progressDialog;
    String url;
    connectAsyncTask(String urlPass){
        url = urlPass;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(DisplayOnMapActivity.this);
        progressDialog.setMessage(getResources().getString(R.string.waitCoord));
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }
    @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);   
        progressDialog.hide();        
        if(result!=null){
            drawPath(result);
        }
    }
}

public void drawPath(LatLng src, LatLng dest) {
    String url = makeURL(src.latitude,src.longitude,dest.latitude,dest.longitude);
    new connectAsyncTask(url).execute();
}

// decodes encoded String into PolyLine object
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;
}

You will also need the JSONParser class:

public class JSONParser {

static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
public JSONParser(){

}
public JSONObject makeHttpRequest(String url){
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    try {
        HttpResponse httpresponse = httpclient.execute(httppost);
        if(httpresponse!=null){
            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 {
        if(is!=null){
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while((line = reader.readLine())!=null){
                    sb.append(line+"\n");   
                    }
                is.close();
                json = sb.toString();
                try {
                    jobj = new JSONObject(json);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    } catch (Exception e){
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jobj;
}

public String getJSONFromUrl(String url) {
    // Making HTTP request
    try {
        // defaultHttpClient
        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) {
        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;
    }
}
5
  • note that in my case I'm using urlString.append("&sensor=false&mode=walking&alternatives=true");. You should use mode=driving Commented Jul 28, 2014 at 10:30
  • can you explain this a little? what does this line of code do: List<LatLng> list = decodePoly(encodedString);
    – Branky
    Commented Jul 28, 2014 at 10:30
  • it decodes the received encoded String into a PolyLine object (the oone that will be drawn). I forgot to add the code for that function, let me edit my answer Commented Jul 28, 2014 at 10:33
  • thanks for the complete answer but how can I add my points to the route?
    – Branky
    Commented Jul 28, 2014 at 11:04
  • use Markers, see documentation here: developers.google.com/maps/documentation/android/marker Commented Jul 28, 2014 at 15:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.