Google Maps setCenter

Center 1st worksI wasted a bit of time trying to figure out why my 5 lines of Google map JavaScript was not working. I created a simple Google map to center the map on a given point and add a marker overlay. It appears that the order of setting the center and the adding the overlay is critical. In the first case, I set the center and added the overlay and the result is as expected.
Center last breaksIn the second case, if I add the overlay before I center the map, I get a blank map — and on Firefox with Firebug installed I see that following error:


this.k has no properties (main.js line 542)
L.prototype.Na=function(a){return this.k.getProjection().fromLatLngToPixel(a,thi...

Here is what the Google Map API documentation has to say about setCenter method: Sets the map view to the given center. Optionally, also sets zoom level and map type. The map type must be known to the map. See the constructor, and the method addMapType(). This method must be called first after construction to set the initial state of the map. It is an error to call other operations on the map after construction.

Here is the correct way of constructing a map:


function load() {
  if (GBrowserIsCompatible()) {
    var ct = new GLatLng(37.4419, -122.1419);
    var map = new GMap2(document.getElementById("map"));
    map.setCenter(ct, 12);
    // now add add the overlays ...
    map.addOverlay(new GMarker(ct));
  }
}

Leave a Reply