阿尔伯特,我认为您担心的是您的代码无法正常工作。在这里,下面的代码非常适合我。我认为您缺少URIUtil.encodeQuery
将字符串转换为 URI。
我正在使用 gson 库,下载它并将其添加到您的路径中。
要获取用于 gson 解析的类,您需要转到jsonschema2pojo。只需在浏览器上触发http://maps.googleapis.com/maps/api/geocode/json?address=Sayaji+Hotel+Near+balewadi+stadium+pune&sensor=true ,获取结果并将其粘贴到此站点上。它会为你生成你的 pojo。您可能还需要添加一个 annotation.jar。
相信我,工作很容易。不要沮丧。
try {
URL url = new URL(
"http://maps.googleapis.com/maps/api/geocode/json?address="
+ URIUtil.encodeQuery("Sayaji Hotel, Near balewadi stadium, pune") + "&sensor=true");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output = "", full = "";
while ((output = br.readLine()) != null) {
System.out.println(output);
full += output;
}
PincodeVerify gson = new Gson().fromJson(full, PincodeVerify.class);
response = new IsPincodeSupportedResponse(new PincodeVerifyConcrete(
gson.getResults().get(0).getFormatted_address(),
gson.getResults().get(0).getGeometry().getLocation().getLat(),
gson.getResults().get(0).getGeometry().getLocation().getLng())) ;
try {
String address = response.getAddress();
Double latitude = response.getLatitude(), longitude = response.getLongitude();
if (address == null || address.length() <= 0) {
log.error("Address is null");
}
} catch (NullPointerException e) {
log.error("Address, latitude on longitude is null");
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Geocode http 有效,我刚刚解雇了它,结果如下
{
"results" : [
{
"address_components" : [
{
"long_name" : "Pune",
"short_name" : "Pune",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Pune",
"short_name" : "Pune",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Maharashtra",
"short_name" : "MH",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Pune, Maharashtra, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 18.63469650,
"lng" : 73.98948670
},
"southwest" : {
"lat" : 18.41367390,
"lng" : 73.73989109999999
}
},
"location" : {
"lat" : 18.52043030,
"lng" : 73.85674370
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 18.63469650,
"lng" : 73.98948670
},
"southwest" : {
"lat" : 18.41367390,
"lng" : 73.73989109999999
}
}
},
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
编辑
关于“答案不包含足够的细节”
从所有研究中,您期望谷歌地图可以参考位置、区域、城市的每一种组合。但事实仍然是谷歌地图在其自身的上下文中包含地理和反向地理。你不能指望它有一个像Sayaji Hotel, Near balewadi stadium, pune
. Web google maps 会为您找到它,因为它使用更广泛的Search
丰富的 google 后端。google api 的唯一反向地理地址是从他们自己的 api 接收的。对我来说,这似乎是一种合理的工作方式,考虑到我们的印度地址系统有多复杂,第二个十字路口可能离第一个十字路口很远:)