javascriptjquerygoogle-maps-api-3google-geocoding-api

Get City Name from Zip Code google geocoding


I've found code on this site to get the sate from a zipcode, but I also need to get the city name.

Here is my code for getting the state: (Note I also use jQuery)

var geocoder = new google.maps.Geocoder();

    $('.zip').bind('change focusout', function () {
        var $this = $(this);
        if ($this.val().length == 5) {
            geocoder.geocode({ 'address': $this.val() }, function (result, status) {
                var state = "N/A";
                //start loop to get state from zip
                for (var component in result[0]['address_components']) {
                    for (var i in result[0]['address_components'][component]['types']) {
                        if (result[0]['address_components'][component]['types'][i] == "administrative_area_level_1") {
                            state = result[0]['address_components'][component]['short_name'];
                            // do stuff with the state here!
                            $this.closest('tr').find('select').val(state);
                        }
                    }
                }
            });
        }
    });  

Solution

  • Just add result[0]['address_components'][1]['long_name']

    So it would be

    var geocoder = new google.maps.Geocoder();
    
    $('.zip').bind('change focusout', function () {
        var $this = $(this);
        if ($this.val().length == 5) {
            geocoder.geocode({ 'address': $this.val() }, function (result, status) {
                var state = "N/A";
                var city = "N/A";
                //start loop to get state from zip
                for (var component in result[0]['address_components']) {
                    for (var i in result[0]['address_components'][component]['types']) {
                        if (result[0]['address_components'][component]['types'][i] == "administrative_area_level_1") {
                            state = result[0]['address_components'][component]['short_name'];
                            // do stuff with the state here!
                            $this.closest('tr').find('select').val(state);
                            // get city name
                            city = result[0]['address_components'][1]['long_name'];
                            // Insert city name into some input box
                            $this.closest('tr').find('.city').val(city);
                        }
                    }
                }
            });
        }
    });