谷歌地图方向Api无法执行路径/路径请求

时间:2014-10-13 23:35:51

标签: android google-maps google-maps-api-2 directions

我正在尝试在我的应用中实现一项功能,该功能使用Google Maps API路线在地图中绘制路径(从A到B)。由于某种原因,似乎应用程序甚至无法提出请求。

这是logcat报告的内容: enter image description here

这是我用来做的课程:

public class DrawPath {

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

    MainActivity actividadPrincipal;


    public DrawPath(MainActivity actividadPrincipal){
        this.actividadPrincipal = actividadPrincipal;
    }


    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;
    }

    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 = actividadPrincipal.googleMap.addPolyline(new PolylineOptions()
                    .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude,   dest.longitude))
                    .width(2)
                    .color(Color.BLUE).geodesic(true));
                }
        } 
        catch (JSONException e) {

        }
    } 

    // Parser Class
    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;

    }

    //First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to getJSONFromUrl function.
    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="+Double.toString(sourcelat)+","+Double.toString( sourcelog));// from
        urlString.append("&destination="+Double.toString(destlat)+","+Double.toString(destlog));// to
        urlString.append("&sensor=false");
        urlString.append("&mode=driving");
        urlString.append("&alternatives=true");
        return urlString.toString();
 }
}

改编自此Answer : Draw path between two points using Google Maps Android API v2
现在,我检查了Directions Api Documentation,但没有找到与此问题相关的任何内容。

这就是我从onCreate底部调用上面的函数的方法(我还没有设计一个按钮)

//test
    DrawPath dPath = new DrawPath(this);
    String path = dPath.makeURL(markers.get(0).marker.getPosition().latitude,
            markers.get(0).marker.getPosition().longitude,
            markers.get(1).marker.getPosition().latitude, 
            markers.get(1).marker.getPosition().longitude);
    dPath.drawPath(path);   

我检查了链接,我发现它没有任何问题。也许我错过了许可?但在这种情况下会引发例外。

我尝试将http更改为https并在请求结束时添加“&amp; key = myApiKey”,因为@ 3amoura已经消化了,但是出现了相同的错误。

更新
在修复了一些小东西并硬编码网址以请求http://maps.googleapis.com/maps/api/directions/json?origin=Granada&destination=Malaga&sensor=false它有效,所以问题在于makeUrl,我一定是做错了

2 个答案:

答案 0 :(得分:1)

它还返回距离和路线,只需要调用方法drawPath(),

步骤1 //全局声明这些变量

GoogleMap googleMap;
Polyline line;
Double starting_lat,starting_lng;

步骤1. // **在您想要绘制路线的地方调用此处,并在此处开始经纬度,

          String urlTopass1 = makeURL(starting_lat,
                starting_lng, location.getLatitude(),
                location.getLongitude());
           new connectAsyncTask(urlTopass1).execute();

// **

第2步。

private class connectAsyncTask extends AsyncTask<Void, Void, String> {
        String url;
    connectAsyncTask(String urlPass) {
        url = urlPass;
        Log.e("test", " :---- 000 " + url);
    }

    @Override
    protected void onPreExecute() {

        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);
        // progressDialog.hide();
        if (result != null) {
            drawPath(result);
        }
    }
}

第3步。

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();
}

public class JSONParser {

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

    // constructor
    public JSONParser() {
    }

    public String getJSONFromUrl(String url) {

        // Making HTTP request
        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) {
            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;

    }
}

第4步。

public void drawPath(String result) {
    try {

        if (line != null) {
            Log.i("removing line", "removed");
            googleMap.clear();
        }

        googleMap.addMarker(new MarkerOptions().position(passLatLng).icon(
                BitmapDescriptorFactory.defaultMarker()));
        marer= googleMap
                .addMarker(new MarkerOptions().position(driverLatLng).icon(
                        BitmapDescriptorFactory
                                .fromResource(R.drawable.icon)));
        try {

            final JSONObject json = new JSONObject(result);

            Log.e("test", "json  :p==  " + json);
            JSONArray routeArray = json.getJSONArray("routes");
            JSONObject routes = routeArray.getJSONObject(0);
            Log.e("test", "routes :==  " + routes);

            JSONArray newTempARr = routes.getJSONArray("legs");
            JSONObject newDisTimeOb = newTempARr.getJSONObject(0);
            Log.e("test", "newDisTimeOb :==  " + newDisTimeOb);

            JSONObject distOb = newDisTimeOb.getJSONObject("distance");

            String tempDist[] = distOb.getString("text").toString()
                    .split(" ");

            double tempDoubleDist = Double.valueOf(tempDist[0].replace(",",
                    ""));
            totalKm = String.valueOf(tempDoubleDist);

            int dist = (int) tempDoubleDist;

            JSONObject overviewPolylines = routes
                    .getJSONObject("overview_polyline");
            String encodedString = overviewPolylines.getString("points");
            List<LatLng> list = decodePoly(encodedString);

            PolylineOptions options = new PolylineOptions().width(5)
                    .color(Color.BLUE).geodesic(true);
            for (int z = 0; z < list.size(); z++) {
                LatLng point = list.get(z);
                options.add(point);
            }
            line = googleMap.addPolyline(options);
            Log.e("checking LatLng of pass bef moveCamera", ""
                    + passLatLng.latitude + "," + passLatLng.longitude);
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(passLatLng));
            if (dist > 2 && dist <= 5) {
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(13.0f));
                mapZoomLevel = 12;
            } else if (dist > 5 && dist <= 10) {
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));
                mapZoomLevel = 11;
            } else if (dist > 10 && dist <= 20) {
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(11.0f));
                mapZoomLevel = 11;
            } else if (dist > 20 && dist <= 40) {
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(10.0f));
                mapZoomLevel = 10;
            } else if (dist > 40 && dist < 100) {
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(9.0f));
                mapZoomLevel = 9;
            } else if (dist > 100 && dist < 200) {
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(8.0f));
                mapZoomLevel = 8;
            } else if (dist > 200 && dist < 400) {
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(7.0f));
                mapZoomLevel = 7;
            } else if (dist > 400 && dist < 700) {
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(6.0f));
                mapZoomLevel = 7;
            } else if (dist > 700 && dist < 1000) {
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(5.0f));
                mapZoomLevel = 6;
            } else if (dist > 1000) {
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(4.0f));
                mapZoomLevel = 5;
            } else {
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(14.0f));
                mapZoomLevel = 14;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

第5步。

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;
}

答案 1 :(得分:0)

问题在于makeUrl正在制作网址的方式,我将其更改为更简单的方式,现在它可以正常工作。

    public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
        String url = "https://maps.googleapis.com/maps/api/directions/json" +
                "?origin="+Double.toString(sourcelat)+","+Double.toString(sourcelog) +
                "&destination="+Double.toString(destlat)+","+Double.toString(destlog) +
                "&sensor=false" +
                "&mode=walking" +
                "&alternatives=true";

        return url;
 }