如何使用 Google 地图地理编码器获取城市

how to get the city using Google Maps Geocoder


我正在使用 Wordpress 开发一个网站,并且我正在使用一个允许插入名为 "Property" 的自定义 post 的主题;此功能在自定义页面模板内处理。在此页面内,我可以添加 属性 的地址,其中包含自动完成地理编码器建议。这是代码:

this.initAutoComplete = function(){
            var addressField = this.container.find('.goto-address-button').val();
            if (!addressField) return null;

            var that = thisMapField;
            $('#' + addressField).autocomplete({
                source: function(request, response) {
                    // TODO: add 'region' option, to help bias geocoder.
                    that.geocoder.geocode( {'address': request.term }, function(results, status) {
                        //$('#city').val(results.formatted_address);

                        response($.map(results, function(item) {
                            $('#city').val(item.formatted_address);
                            return {
                                label: item.formatted_address,
                                value: item.formatted_address,
                                latitude: item.geometry.location.lat(),
                                longitude: item.geometry.location.lng()
                            };
                        }));
                    });
                },
                select: function(event, ui) {
                    that.container.find(".map-coordinate").val(ui.item.latitude + ',' + ui.item.longitude);
                    var location = new window.google.maps.LatLng(ui.item.latitude, ui.item.longitude);
                    that.map.setCenter(location);
                    // Drop the Marker
                    setTimeout(function(){
                        that.marker.setValues({
                            position: location,
                            animation: window.google.maps.Animation.DROP
                        });
                    }, 1500);
                }
            });
        }

单击地址时,地图会根据收到的坐标绘制标记。我想从单击的地址中提取城市并将该值放在另一个输入字段中。我怎样才能做到这一点?谢谢!

正在看documentation 你需要访问 address_components 并寻找类型的地方,政治,所以像这样:

var city = '';
item.address_components.map(function(e){ 
    if(e.types.indexOf('locality') !== -1 &&
       e.types.indexOf('political') !== -1) {
        city = e.long_name;
    }
});

$('#city').val(city);