2017-10-06 159 views
-1

我已经功能给我Lat Long网从地址:天气预报如何避免在谷歌地图API -java OVER_QUERY_LIMIT

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();
我怎样才能避免这个问题? 也在这个函数中有些地址没有错误,但是当我再次运行这个函数时,我得到这些以前很好的地址的错误。

回答

1

这是我学到了什么,当我用这个API的工作:

  1. 据“慢”。我的意思是,这可能是一个代价高昂的操作。
  2. Google建议不要每次都要进行地理编码,而是在创建点时存储(经纬度)点。
  3. Google每天最多有2500个地理编码请求的配额。
  4. 在循环中发送10个以上地理编码请求后,Google API会引发OVER_QUERY_LIMIT异常。

请仔细阅读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

有一个Java客户端的谷歌地图的网络服务,你可以在GitHub上找到:

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限度内。

阅读文档和javadoc并尝试它。

我希望这有助于!

0

刚刚返回值:

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

为我工作!