2017-10-06 156 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); 
} 

爲我工作!