如何将城市或州名转换为邮政编码

3

我该如何使用Geocoder API或其他方法,在javascript或angularjs中将城市或州名称转换为邮政编码?我想从用户输入中进行转换。


你正在展示谷歌地图吗?(如果没有,我有一些建议。) - Matt
4个回答

1
感谢大家。我已经解决了.....:) 这里是代码:

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();

    };

});

};


0

这是一个工厂示例:

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)

除了模块化和可重用性之外,这段代码需要放在工厂中的特定好处或原因吗? - Matty J

0

只要你使用谷歌地图,就没问题,否则就违反了他们的服务条款。 - Matt

0

当然,邮政编码不一定与地点有关,而是与投递路线有关。美国邮政局控制着邮政编码,并根据投递邮件的效率进行必要的重新排列。许多人已经习惯了认为邮政编码恰好代表某个城市或城市区域,但它并不是静态的。在美国的42,000个5位数邮政编码中,大约有4%的编码每个月都会更改,因此无论您从哪里获取城市/州/邮政编码数据,请确保它每月都由美国邮政局更新。

除了Google Maps之外,还有许多商业服务可以提供您所需的信息。快速搜索“邮政编码API”即可找到。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接