我试图从Google地理定位API结果中仅获取县名。不幸的是,该县并不总是在结果的同一地点,所以我需要通过识别键administrative_area_level_2
这是我的电话:
$.getJSON( {
url : 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&sensor=true',
data : {
sensor : false
},
success : function( data, textStatus ) {
var county = data.results[0].address_components[4].long_name;
alert('County: ' + county);
}
});
这适用于我所在的县,但不适用于其他县,因为address_components[4]
并不总是县。但是,我注意到该县始终与administrative_area_level_2
以下是一个示例回复:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Edge of Everglades Trail",
"short_name" : "Edge of Everglades Trail",
"types" : [ "route" ]
},
{
"long_name" : "Homestead",
"short_name" : "Homestead",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Miami-Dade County",
"short_name" : "Miami-Dade County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Florida",
"short_name" : "FL",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "33031",
"short_name" : "33031",
"types" : [ "postal_code" ]
}
],
...
我如何获得与administrative_area_level_2
类型相关联的“long_name”?
答案 0 :(得分:9)
要从地址组件数组获取administrative_area_level_2
,您可以使用Array.prototype.filter()和Array.prototype.includes()个功能。
var filtered_array = data.results[0].address_components.filter(function(address_component){
return address_component.types.includes("administrative_area_level_2");
});
var county = filtered_array.length ? filtered_array[0].long_name: "";
您还可以使用反向地理编码直接搜索administrative_area_level_2
$.getJSON( {
url : 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&result_type=administrative_area_level_2',
data : {
sensor : false
},
success : function( data, textStatus ) {
var filtered_array = data.results[0].address_components.filter(function(address_component){
return address_component.types.includes("administrative_area_level_2");
});
var county = filtered_array.length ? filtered_array[0].long_name: "";
alert('County: ' + county);
}
});
我希望这有帮助!