Reputation: 16736
Would someone tell me how to center on a country by name on the Google Maps API v3? I know how to do it in v2, but need to do it in v3.
Upvotes: 25
Views: 34348
Reputation: 3128
You could use Geocoding to lookup the Lat/Lng of the country. Take a look at this sample from Google.
Basically you need to do something like this:
var country = "Germany";
var geocoder;
geocoder.geocode( {'address' : country}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
});
In your initialize function you'll need to set the value of the geocoder object, like this:
geocoder = new google.maps.Geocoder();
You'd need to workout what an appropriate zoom level would be, and then set that after you have centered the map.
Upvotes: 56
Reputation: 1241
This code working for me:
let geocoder = new google.maps.Geocoder();
let location = "England";
geocoder.geocode({ 'address': location }, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
} else {
alert("Could not find location: " + location);
}
});
Upvotes: 4
Reputation: 10258
The only way I know how to do it would be by having a list of the countries and their respective Lat and Lng, with that information known you could use the following code.
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
Out of curiosity, how would you do it in v2?
Upvotes: 0