Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

android - Getting direction between two points in Google Maps, crossing specific points

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...