使用谷歌地图API JSON获取纬度和经度有时为NULL [英] Get the lat and lng sometime is NULL with google map api json
问题描述
通过以下代码将大量地址转换为经纬度时,有时结果为空. 我认为原因是过多使用了此网址,因此获取了空值. 如何解决此问题以获取正确的经纬度?
When lots of address be transformed to lat&lng by following code, sometimes the result is null. I think that reason is using this url too much, so getting null value. how do I solve this problem to get correct lat&lng?
String transformerUrl = "http://maps.google.com/maps/api/geocode/json?address=%s&language=zh-TW&sensor=false®ion=tw";
private String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public String[] getLocationInfoByAddress(String address)
throws IOException, JSONException {
String[] latLngStr = new String[2];
String encodeAddress = URLEncoder.encode(address, "Utf-8");
String formatAddress = String.format(transformerUrl, encodeAddress);
InputStream is = new URL(formatAddress).openConnection().getInputStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is,
Charset.forName("UTF-8")));
String jsonText = readAll(rd);
//System.out.println(jsonText);
try {
JSONArray arr = new JSONObject(jsonText)
.getJSONArray("results");
for (int i = 0; i < arr.length(); ++i) {
if (arr.getJSONObject(i).get("geometry") != null) {
Object lat = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").get("lat");
Object lng = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").get("lng") ;
latLngStr[0] = lat.toString();
latLngStr[1] = lng.toString();
break;
}
}
} catch (JSONException e) {
}
} finally {
is.close();
}
return latLngStr;
}
推荐答案
检查返回的状态,然后再使用结果.
Check the returned Status before using the result.
Google Maps地理编码网络服务受配额和费率限制.如果您不遵守这些规定,则会获得OVER_QUERY_LIMIT的状态.
The Google Maps Geocoding Web Service is subject to a quota and a rate limit. If you don't comply to those, you will get a status of OVER_QUERY_LIMIT.
如果您没有在您的密钥中添加 URL(我在您的问题中没有看到),向您的请求添加密钥可能会允许您拥有自己的独立配额(仅在共享服务器上才真正适用).
If you aren't including a key in your URL (which I don't see in your question), adding a key to your request may allow you your own independent quota (only really applicable if you are on a shared server).
如果这没有帮助,则需要限制您的请求以符合配额/费率限制.有关如何在StackOverflow上执行此操作的问题.
If that doesn't help, you need to throttle your requests to comply with quota/rate limit. There are questions on how to do that on StackOverflow.
这篇关于使用谷歌地图API JSON获取纬度和经度有时为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!