问题
I am attempting to get only the county name from a Google geolocation API result. Unfortunately, the county is not always in the same spot for the results so I need to grab it by an identifying key administrative_area_level_2
Here's my call:
$.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);
}
});
This works for the county I am in, but not for other counties because address_components[4]
is not always the county. I did notice, however, that the county is always associated with administrative_area_level_2
Here's an example response:
{
"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" ]
}
],
...
How would I go about getting the "long_name" associated with administrative_area_level_2
type?
回答1:
In order to get administrative_area_level_2
from address components array you can use Array.prototype.filter() and Array.prototype.includes() functions.
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: "";
You can also search directly the administrative_area_level_2
with reverse geocoding
$.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);
}
});
I hope this helps!
来源:https://stackoverflow.com/questions/44592202/how-to-get-only-administrative-area-level-2-from-google-geocoding-api