正在从谷歌地图请求解析城市/州
Parsing city/state from Google Maps request
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)
}
这就是我现在使用的,大约90%的时间都是这样。有时,formatted_address
包含一个城镇和一个城市以及州,有时只是城镇和城市,有时是你能梦想的一切。
我还没有找到一种始终从谷歌地图API结果中获取城市/州的一致方法。你们有人有吗?谢谢
谷歌在其页面上使用的一个响应示例:
{
"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
}
}
}
} ]
}
有时这些字段没有值,有时有值。
为什么解析formatted_address
?
有address_components,您可以浏览它们并查找具有的
"types": [ "administrative_area_level_1", "political" ]// the state
"types" : [ "locality", "political" ]//the city
以下是一个示例:http://jsfiddle.net/doktormolle/QWPCL/
到目前为止,这似乎对我有效。。。
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
相关文章:
- ajax请求的顺序总是不同的
- Meteor如何接收HTTP请求
- 有没有一种方法可以防止img get请求使用css或js发生
- 从城市名称获取惊喜
- 从ajax请求中获取javascript对象
- JSONP请求返回结果,但也触发error_callback
- 在localhost Dev Box上测试JSONP请求的最佳方式
- Ajax请求文档就绪会导致jquery加载缓慢
- MockJax没有在JavaScript应用程序中发送对我AJAX请求的响应
- 正在传递JSONP标头's数据参数到另一个文件中的AJAX请求
- 在openshift node js应用程序中获取请求
- 反应路由器弄乱了请求网址
- 州和城市选择框类似于国家细分页面
- 在我的情况下,如何进行http请求
- 使用密码对话框Javascript请求帮助
- servlet中的请求对象,而不是从jsp接收参数值
- 否'访问控制允许来源'标头存在于IISNOde中请求的资源(AngularJS+NodeJs)上
- JavaScript代码未正确检查ajax请求
- node.js请求数据事件未在CORS ajax调用中触发
- 正在从谷歌地图请求解析城市/州