Center on a country by name in Google Maps API v3

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.

Answers


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.


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

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?


Need Your Help

How do I map to a lookup table using Entity Framework Code First with Fluent API

database asp.net-mvc-4 ef-code-first fluent

I'm new to asp.net mvc and entity framework code first apporach, I'm not that keen on databases either. I apologise in advance for wrong terminology or the way I understand things.

Find out which javascript function is fired on click...

javascript javascript-events

Is there a way to find out which javascript function is fired by click on a certain button?