views:

486

answers:

2

I'm using the Google Maps API (v2) and would like to center the map onload to a country (for example england).

At the moment i center the map using:

map.setCenter(new GLatLng( 43.907787,-79.359741), 9);

But this obviously requires longitude and Latitude.

Any way to do this by inserting a name of a country?

+2  A: 

Turning a location name or address into a latitude/longitude like this is called geocoding. Google Maps API now includes this capability: see http://code.google.com/apis/maps/documentation/services.html#Geocoding

They include a sample application where you can type in an address, and it does work to simply type a country name. I don't know if they are going to the exact center of the country.

JacobM
+1 for assisted answer
Shadi Almosri
+5  A: 
var country = "United States"
var map = new GMap2($("#map")[0]);
map.setUIToDefault();

var geocoder = new GClientGeocoder();
geocoder.getLatLng(country, function (point) {
  if (!point) {
    // Handle error
  } else {
    map.setCenter(point, 8, G_PHYSICAL_MAP);
  }
});
Bob Aman
The question that i accepted i actually used at first to implement it, but then i moved over to your code which works better in my setup...thanks
Shadi Almosri
changed this to accepted answer as it's only fair as it's the one finally implemented
Shadi Almosri
The geocoder also returns ExtendedData which contains a suggested size for the target. [Note that the box isn't a perfect fit for the target location. It's just there to provide sensible zooming.] But that could be exactly what you need in this case, so that you get a different zoom when you centre on England than when you centre on Russia.See http://econym.org.uk/gmap/example_geo3.htm
Mike Williams