Albert,我认为你担心的是你的代码无法运行。下面的代码对我来说运行得非常好。我认为你缺少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();
}
地理编码的 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"
}
编辑
关于“答案缺乏足够的细节”
你期望谷歌地图包含每个地点、区域和城市组合的参考信息,但事实是谷歌地图只在其自己的上下文中包含地理和反向地理信息。你不能期望它拥有像普纳市巴勒瓦迪体育场旁萨雅吉酒店
这样的组合信息。Web版谷歌地图可以定位到这个位置,因为它使用了更全面的搜索
功能,谷歌API只能从他们自己的API中获取反向地理地址。对我来说,这似乎是一种合理的工作方式,考虑到我们印度的地址系统有多么复杂,第二十字路口可能与第一十字路口相隔数英里 :)