在Google地图中沿道路画一条线

Gra*_*ant 2 android google-maps google-maps-api-3

我想在Android的Google Maps v2中沿道路画一条线。因此,我对此进行了搜索,并在此处此处找到了这些示例代码, 但是不幸的是,这两个示例都不适合我。第一个给了我一个强制关闭的例外。有人有这个可行的例子吗?

谢谢!

She*_*bu. 5

首先创建普通的Googlemaps V2应用,在该方法中

1)字符串myurl = makeURL(source_latitude,source_longitude,destinaton_latitude,destinaton_longitude);

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();
        }
Run Code Online (Sandbox Code Playgroud)

2)调用异步任务

新的connectAsyncTask(myurl).execute();

异步类

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

        connectAsyncTask(String urlPass) 
        {
    url = urlPass;
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Fetching route, Please wait...");
        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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

3) 画一条路

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);
                Polyline line = googleMap.addPolyline(new PolylineOptions().add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude)).width(4).color(Color.BLUE).geodesic(true));
            }

        } catch (JSONException e) {

        }
    }

    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;
    }
Run Code Online (Sandbox Code Playgroud)

4)现在创建一个新类

public class JSONParser {

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

    // constructor
    public JSONParser() {
    }

    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();`enter code here`
        } 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;

    }
}
Run Code Online (Sandbox Code Playgroud)