Search code examples
google-mapsdictionarygoogle-maps-api-3geo

How to center a google map around a country if you just have the country name


I have a page about hiking in various countries. I am trying to make a page like that for each country, but not sure how to automatically center the google map around a country and also have it adjust the focus depending on the size of the country.

Here are my problem pages:

http://www.comehike.com/outdoors/country.php?country_id=6&country_name=Belarus

http://www.comehike.com/outdoors/country.php?country_id=1&country_name=United%20States

You see how the centering and focus size is static? That is because I currently use this code to center the map:

function initialize( )
{
    var myLatlng = new google.maps.LatLng(37.775, -122.4183333);

    var myOptions =
    {
      zoom: 2,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

But that is only because I am not sure how to do it by country name, and adjust the size automatically. How can I do this all by passing a country name into the initialize function?

Thanks!


Solution

  • You can transform country name to the coordinates using Geocoding service. Example provided by Google centers a map but it does not zoom it. To zoom it you should use map.fitBounds() method using LatLngBounds object returned by the geocoder. This is an example code:

    var myLatlng = new google.maps.LatLng(37.775, -122.4183333);
    
    var myOptions =
    {
        zoom: 2,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    var address = "Belarus";
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            map.fitBounds(results[0].geometry.bounds);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });