代码之家  ›  专栏  ›  技术社区  ›  Aman Kush

在android中使用google maps v2查找最近的加油站,并显示通往加油站的路线

  •  1
  • Aman Kush  · 技术社区  · 9 年前

    StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
            googlePlacesUrl.append("location=" + source.latitude + "," + source.longitude);
            googlePlacesUrl.append("&radius=" + PROOXIMITY_RADIUS);
            googlePlacesUrl.append("&types=" + "gas_station");
            googlePlacesUrl.append("&sensor=true");
            googlePlacesUrl.append("&key=" + GOOGLE_API_KEY);
    

    使用上述代码,我正在创建url以获取最近的加油站。

    public String read(String httpUrl){
            String httpData = "";
            InputStream stream = null;
            HttpURLConnection urlConnection = null;
            try{
                URL url = new URL(httpUrl);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();
                stream = urlConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                StringBuffer buf = new StringBuffer();
                String line = "";
                while((line = reader.readLine()) != null){
                    buf.append(line);
                }
                httpData = buf.toString();
                reader.close();
            } catch (Exception e) {
                Log.e("HttpRequestHandler" , e.getMessage());
            } finally {
                try {
                    stream.close();
                    urlConnection.disconnect();
                } catch (Exception e){
                    Log.e("HttpRequestHandler" , e.getMessage());
                }
            }
    
            return httpData;
        }
    

    在此之后,我正在解析响应。

    但我想做的是找到最近的一个?我可以用经纬度来计算距离,但我认为一定有更简单的方法?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Community Mohan Dere    6 年前

    最直接的方法是使用 rankby=distance 请求中的参数。

    指定结果的列出顺序。请注意,如果指定了半径(在上述所需参数下描述),则不得包括rankby。可能的值为:

    突出(默认) 。此选项根据结果的重要性对结果进行排序。排名将有利于指定区域内的突出位置。显著性可能会受到位置在谷歌索引中的排名、全球人气和其他因素的影响。

    距离

    https://developers.google.com/places/web-service/search#PlaceSearchRequests

    代码段如下(您可以删除 radius rankby

    StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    googlePlacesUrl.append("location=" + source.latitude + "," + source.longitude);
    googlePlacesUrl.append("&rankby=distance");
    googlePlacesUrl.append("&type=" + "gas_station");
    googlePlacesUrl.append("&key=" + GOOGLE_API_KEY);
    

    sensor 参数,该参数在很久以前已弃用,不再使用。请注意 types 参数无效,应使用 type

    类型 将结果限制为与指定类型匹配的位置。只能指定一种类型(如果提供了多个类型,则忽略第一个条目之后的所有类型)

    最近的加油站将是第一个响应。