【问题标题】:how to get the city using Google Maps Geocoder如何使用 Google Maps Geocoder 获取城市
【发布时间】:2015-06-08 20:13:05
【问题描述】:


我正在使用Wordpress 开发一个网站,并且我正在使用一个允许插入名为“Property”的自定义帖子的主题;此功能在自定义页面模板中处理。在这个页面中,我可以添加属性的地址,它具有自动完成地理编码器的建议。代码如下:

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

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

【问题讨论】:

    标签: javascript jquery wordpress google-maps google-geocoder


    【解决方案1】:

    看着documentation 您需要访问 address_components 并查找类型 locality,political,所以是这样的:

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

    【讨论】:

      猜你喜欢
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 2012-11-18
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      相关资源
      最近更新 更多