简体   繁体   中英

how to get the city using Google Maps Geocoder


I'm developing a website using Wordpress and I'm using a theme that allows to insert custom post called "Property"; this features is handled inside a custom page template. Inside this page I can add the address of the property, which has the autocomplete geocoder suggestion. Here is the code:

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

When an address is clicked, the maps draw a maker with the coordinates received. I would like to extract the city from the address clicked and put that value on another input field. How can I do that? Thanks!

looking at documentation you need to access address_components and look for type locality, political, so something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM