我该如何使用Geocoder API或其他方法,在javascript或angularjs中将城市或州名称转换为邮政编码?我想从用户输入中进行转换。
我该如何使用Geocoder API或其他方法,在javascript或angularjs中将城市或州名称转换为邮政编码?我想从用户输入中进行转换。
function getCity( options) {
var geocoder = new google.maps.Geocoder(),
request;
if( options.latitude ) {
request= { 'latLng': new google.maps.LatLng( options.latitude, options.longitude ) };
} else {
request= { 'address': options.address };
};
geocoder.geocode( request, function( results, status ) {
if ( status == google.maps.GeocoderStatus.OK ) {
console.log( results );
geocoder.geocode( request, function( results, status ) {
if ( status == google.maps.GeocoderStatus.OK ) {
console.log( results );
var latitude = results[0].geometry.location.jb;
var longitude = results[0].geometry.location.kb;
var latlng = new google.maps.LatLng(latitude, longitude)
alert(latlng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
//no result, check addresses
for( var resultIndex = 0; resultIndex < results.length; resultIndex++ ) {
var addresses = results[resultIndex].address_components;
for( var addressIndex = 0; addressIndex < addresses.length; addressIndex++ ) {
var types = addresses[addressIndex].types;
for( var typeIndex = 0; typeIndex < types.length; typeIndex++ ) {
if( types[typeIndex] == 'postal_code' ) {
alert(addresses[addressIndex].long_name) ;
return;
};
};
};
};
});
} else {
console.log( 'error: ' + status );
// complete();
};
});
};
这是一个工厂示例:
feederliteModule.factory('maps', ['$q', function ($q) {
var geocoder = new google.maps.Geocoder();
return {
geocode: function (address) {
var deferred = $q.defer();
geocoder.geocode({
'address': address
}, function (results, status) {
deferred.resolve(results);
// Should also reject if AJAX errors.
});
return deferred.promise;
}
};
}]);
其中address
是输入。
输出应该是json视图,您可以在其中找到邮政编码:
...
{
"long_name": "168751",
"short_name": "168751",
"types": [
"postal_code"
]
}
...
现在你可以像这样从控制器中调用它:
maps.geocode(address)
谷歌为此提供了一个流畅的API。请查看这个Stack Overflow线程,使用GoogleAPI从城市名称获取邮政编码: 从城市名称获取邮政编码的最简单方法
当然,邮政编码不一定与地点有关,而是与投递路线有关。美国邮政局控制着邮政编码,并根据投递邮件的效率进行必要的重新排列。许多人已经习惯了认为邮政编码恰好代表某个城市或城市区域,但它并不是静态的。在美国的42,000个5位数邮政编码中,大约有4%的编码每个月都会更改,因此无论您从哪里获取城市/州/邮政编码数据,请确保它每月都由美国邮政局更新。
除了Google Maps之外,还有许多商业服务可以提供您所需的信息。快速搜索“邮政编码API”即可找到。