地理编码:如何避免谷歌地图api -java中的OVER_QUERY_LIMIT

时间:2017-10-06 16:26:56

标签: java google-maps geocoding

我的功能让我从地址拉长:

 public static String[] getLatLongPositions(String address) throws Exception
  {
    int responseCode = 0;
    String api = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + URLEncoder.encode(address, "UTF-8") + "&sensor=true";
    //System.out.println("URL : "+api);
    URL url = new URL(api);
    HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
    httpConnection.connect();
    responseCode = httpConnection.getResponseCode();
    if(responseCode == 200)
    {
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();;
      Document document = builder.parse(httpConnection.getInputStream());
      XPathFactory xPathfactory = XPathFactory.newInstance();
      XPath xpath = xPathfactory.newXPath();
      XPathExpression expr = xpath.compile("/GeocodeResponse/status");
      String status = (String)expr.evaluate(document, XPathConstants.STRING);
      if(status.equals("OK"))
      {
         expr = xpath.compile("//geometry/location/lat");
         String latitude = (String)expr.evaluate(document, XPathConstants.STRING);
         expr = xpath.compile("//geometry/location/lng");
         String longitude = (String)expr.evaluate(document, XPathConstants.STRING);
         return new String[] {latitude, longitude};
      }
      else
      {
         throw new Exception("Error from the API - response status: "+status+"street "+ address);
      }
    }
    return null;
  }

但是我经常会得到OVER_QUERY_LIMIT,所以我试着睡了一会儿再次运行我的功能添加:

if(status.equals("OVER_QUERY_LIMIT")){
              Thread.sleep(1000);
              getLatLongPositions(address);
          }

但是当getLatLongPositions以递归方式再次运行时,我在此行responseCode = httpConnection.getResponseCode();处得到null 我该如何避免这个问题? 同样在这个函数中,一些地址没有错误但是当我再次运行这个函数时,我得到了这些地址之前的错误。

3 个答案:

答案 0 :(得分:1)

这是我在使用此API时学到的内容:

  1. 这是"慢"。我的意思是,这可能是一项代价高昂的操作。
  2. Google建议不要每次都进行地理编码,而是在创建时存储(lat,long)点。
  3. Google的每日最大地理编码请求数为2500。
  4. 在循环中发送10个以上的地理编码请求后,Google API会引发OVER_QUERY_LIMIT异常。
  5. 请阅读OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

答案 1 :(得分:1)

您可以在github上找到Google Maps Web服务的Java客户端:

https://github.com/googlemaps/google-maps-services-java

虽然这是一个开源项目,但它是由Google员工编写的,并提供了许多可以使用的功能。特别是,您可以在GeoApiContext中为请求设置速率限制:queryRateLimit(int maxQps)

https://googlemaps.github.io/google-maps-services-java/v0.2.3/javadoc/

此客户端库将限制您的请求以保持在允许的QPS限制范围内。

阅读docs和javadoc并试一试。

我希望这有帮助!

答案 2 :(得分:0)

只需返回值:

else if(status.equals("OVER_QUERY_LIMIT"))
{
    Thread.sleep(1000);
    return getLatLongPositions(address);
}

为我工作!