I am using the Google Maps API and currently successfully adding markers based on exact locations, but I would like to also be able to add markers over countries without needing to have the coordinates of that country.
Is this possible?
I am using the Google Maps API and currently successfully adding markers based on exact locations, but I would like to also be able to add markers over countries without needing to have the coordinates of that country.
Is this possible?
Share Improve this question asked Sep 11, 2013 at 14:50 TomTom 13k50 gold badges153 silver badges247 bronze badges2 Answers
Reset to default 14It is highly possible indeed. Use GeoCoder : https://developers.google./maps/documentation/javascript/geocoding
GeoCoder can return the lat / lngs for a country, just by knowing its name.
Assuming you already have a map
:
geocoder = new google.maps.Geocoder();
function getCountry(country) {
geocoder.geocode( { 'address': country }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
getCountry('USA');
getCountry('Brazil');
getCountry('Denmark');
Will place markers on your map in the direct center of USA, Brazil and Denmark.
According to the Maps API, marker.position
is a required property, and it must be of LatLng
type. So at the very least you'd either need to know the coordinates at the centre of the country, or an bounded array of coordinates for the country from which you you can extrapolate the coordinates for the centre.
I believe that if you use the Geocoder with just the country name, the service will provide you with the coordinates for the exact centre of the country. I've not tested this, and I don't know what if there's a limit to how much you can use it, but it would be worth you checking it out as a solution to your question.
For example:
var geo = new google.maps.Geocoder();
geo.geocoder.geocode('Spain', function (data) {
// the coordinates are held in data[0].geometry.location.lat() and data[0].geometry.location.lng().
});