Javascript 从谷歌地图请求解析城市/州
这就是我现在所用的,90%的时间都是这样。有的时候,格式化的地址包含一个城镇和一个城市以及州,有的时候只有城镇和城市,有的时候是你梦想的一切 我还没有找到一种从谷歌地图API结果中获取城市/州的一致方法。你们有人有吗?谢谢 Google在其页面上使用的一个响应示例:Javascript 从谷歌地图请求解析城市/州,javascript,parsing,google-maps-api-3,Javascript,Parsing,Google Maps Api 3,这就是我现在所用的,90%的时间都是这样。有的时候,格式化的地址包含一个城镇和一个城市以及州,有的时候只有城镇和城市,有的时候是你梦想的一切 我还没有找到一种从谷歌地图API结果中获取城市/州的一致方法。你们有人有吗?谢谢 Google在其页面上使用的一个响应示例: var geocoder = new google.maps.Geocoder(); geocoder.geocode({'latLng': foundLoc}, function(results, stat
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': foundLoc}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var loc = getCityState(results);
}
}
});
function getCityState(results)
{
var citystateArray = results[1].formatted_address.split(",",2);
var city = citystateArray[0];
var state = citystateArray[1].substring(1, 3);
return (city + ', ' + state)
}
有时这些字段没有值,有时有值。为什么要解析
格式化的\u地址
有地址_组件,您可以浏览它们并查找具有
{
"status": "OK",
"results": [ {
"types": [ "street_address" ],
"formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"address_components": [ {
"long_name": "1600",
"short_name": "1600",
"types": [ "street_number" ]
}, {
"long_name": "Amphitheatre Pkwy",
"short_name": "Amphitheatre Pkwy",
"types": [ "route" ]
}, {
"long_name": "Mountain View",
"short_name": "Mountain View",
"types": [ "locality", "political" ]
}, {
"long_name": "California",
"short_name": "CA",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "United States",
"short_name": "US",
"types": [ "country", "political" ]
}, {
"long_name": "94043",
"short_name": "94043",
"types": [ "postal_code" ]
} ],
"geometry": {
"location": {
"lat": 37.4219720,
"lng": -122.0841430
},
"location_type": "ROOFTOP",
"viewport": {
"southwest": {
"lat": 37.4188244,
"lng": -122.0872906
},
"northeast": {
"lat": 37.4251196,
"lng": -122.0809954
}
}
}
} ]
}
这里有一个例子:到目前为止,这似乎对我有效
"types": [ "administrative_area_level_1", "political" ]// the state
"types" : [ "locality", "political" ]//the city
你能提供几种不同类型的响应吗?也许可以构造一个能可靠工作的正则表达式。添加了一个恰好具有完整值的响应示例。你可以展示另外两个可能收到的格式化的\u address
示例吗?谢谢。我将只写一些东西来循环遍历它们。如果结果是“street\u address”类型呢?然后您必须解析或使用其他本地化服务
readCityAndStateFromResult: (data) ->
displayName = []
for component in data[0].address_components
if component.types and component.types.length
switch true
when 'locality' in component.types
displayName.push component.long_name
when 'administrative_area_level_1' in component.types or 'administrative_area_level_2' in component.types
displayName.push component.short_name
return displayName.join ', ' if displayName.length
return null