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);
}
}
}
});
}
});
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);
}
}
}
});
}
});
I've rewritten above solution to look more elegant:
var zipCode = '48201';
var country = 'United States';
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': zipCode + ',' + country }, function (result, status) {
var stateName = '';
var cityName = '';
var addressComponent = result[0]['address_components'];
// find state data
var stateQueryable = $.grep(addressComponent, function (x) {
return $.inArray('administrative_area_level_1', x.types) != -1;
});
if (stateQueryable.length) {
stateName = stateQueryable[0]['long_name'];
var cityQueryable = $.grep(addressComponent, function (x) {
return $.inArray('locality', x.types) != -1;
});
// find city data
if (cityQueryable.length) {
cityName = cityQueryable[0]['long_name'];
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With