Reputation: 631
I have a google map which has a marker on it so people can move it around. When they do I'm attempting to reverse geocode the location into a proper address but I only really want the town/city and the country, I don't want the postcode returned
Is it possible to just get the locality without having to use a regex to remove the postcode - which would prob be difficult!
Thanks in advance
Upvotes: 1
Views: 6991
Reputation: 995
I think you can!
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results.length; i++) {
if (results[i].types[0] === "locality") {
var city = results[i].address_components[0].short_name;
var state = results[i].address_components[2].short_name;
alert('Serial=' + i+ ' city=' + city+ ' state=' + state)
};
};
};
};
Upvotes: 1
Reputation: 571
Reverse GeoCoding returns an address_components array containing few objects. (You can print this object in console to get the feel.) Extracting required information from this array is very easy. Now have a look at the code -
function getLatLong(position) {
geocoder = new google.maps.Geocoder();
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
// Reverse Geocoding, Location name from co-ordinates.
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var components=results[0].address_components;
for (var component=0;component<(components.length);component++){
if(components[component].types[0]=="administrative_area_level_1"){
var admin_area=components[component].long_name;
}
if(components[component].types[0]=="country"){
var country=components[component].long_name;
}
if(components[component].types[0]=="postal_code"){
var postal_code=components[component].long_name;
}
}
}
}
}
}
Upvotes: 2
Reputation: 117314
The response didn't only return the address, it also contains the address_components, an array with the specific details of the location, e.g. country, city, street etc. (see https://developers.google.com/maps/documentation/geocoding/#JSON)
fetch the desired components out of this array.
Upvotes: 2