我正在使用这个java libraray
<dependency>
<groupId>com.google.maps</groupId>
<artifactId>google-maps-services</artifactId>
<version>0.1.15</version>
</dependency>
当我执行下面的代码时
public static GeocodingResult getGeocode(String address) {
GeocodingResult[] results;
try {
GeoApiContext context = new GeoApiContext().setApiKey(GOOGLE_KEY);
results = GeocodingApi.geocode(context, address).await();
if (results.length > 0) {
return results[0];
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
GeocodingResult geocode = getGeocode("Imanova 19, Astana");
System.out.println(geocode.geometry.location.lat);
}
结果给出了
INFO: Request: https://maps.googleapis.com/maps/api/geocode/json?key=MY_GOOGLE_KEY&address=Imanova+19%2C+Astana
51.16052269999999
但是,当我尝试从浏览器调用相同的给定请求时,它会产生另一个结果。
问题是,为什么如此以及如何解决?
从评论中进行修改:
https://maps.googleapis.com/maps/api/geocode/json?address=Imanova+19%2C+Astana
的结果{
"results" : [
{
"address_components" : [
{
"long_name" : "Astaná",
"short_name" : "Astaná",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Astana",
"short_name" : "Astana",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Kazajistán",
"short_name" : "KZ",
"types" : [ "country", "political" ]
},
{
"long_name" : "020000",
"short_name" : "020000",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Astaná 020000, Kazajistán",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 51.2903453,
"lng" : 71.7427397
},
"southwest" : {
"lat" : 51.0055461,
"lng" : 70.9179879
}
},
"location" : {
"lat" : 51.16052269999999,
"lng" : 71.47035579999999
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 51.2903453,
"lng" : 71.7427397
},
"southwest" : {
"lat" : 51.0055461,
"lng" : 70.9179879
}
}
},
"partial_match" : true,
"place_id" : "ChIJCUa1fcSARUIRKJKx3Y0U-Zc",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
答案 0 :(得分:0)
这个答案https://stackoverflow.com/a/30749036/1862262完整地描述了我的问题的解决方案。
以同样的方式设置区域
GeocodingResult[] results = GeocodingApi.geocode(context, address).region("KZ").await();
并得到与浏览器中的结果相同的结果。
但我不知道如果没有设置它需要哪个区域。
以下是有关此选项和问题https://developers.google.com/maps/documentation/geocoding/#RegionCodes
的文档