24

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.

3 Answers 3

55

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.

2
  • I thinks this is the cleanest and simplest way to re-position the map... Thanks :)
    – Aamir Shah
    Feb 12, 2014 at 5:02
  • @kzhen this works but it doesn't zoom in that much on some countries like Australia. is there a way to alter this?
    – Red Baron
    Jun 8, 2020 at 20:28
3

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);
          }
      });
0

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?

2
  • you could pass the country name to the geocoder provided in the API, and use the resultant lat/lon just as you've done there.
    – RYFN
    Dec 10, 2010 at 11:59
  • for reference, here you can find a list of countries and their respective center points: github.com/mihai-craita/countries_center_box Jul 29, 2022 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.