javascriptgoogle-mapsscope

Scope of Google Map variable and calling method


I'm playing with the Google Maps API to familiarise myself with JavaScript. I'm a terrible programmer, so please forgive me.

I'm not quite sure why the following code doesn't work, you can check a JSFiddle here: http://jsfiddle.net/m9QLx/

var map;

function initialize() {

var myOptions = {
      center : new google.maps.LatLng(34.053228, -118.259583),
      zoom   : 11,
      zoomControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    },

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

};

google.maps.event.addDomListener(window, 'load', initialize);

map.panTo(new google.maps.LatLng(37.4569, -122.1569));

Everything works fine but I'm not sure why the panTo method doesn't work, as far as I can work out, declaring var map outside of all functions makes it global, I then set map in the initialize() function but outside of this initialize() function the panTo method doesn't work, map appears to be undefined.

I'm sure I'm making a rookie mistake but I can't find an answer (I'm sure I'm Googling the wrong thing).


Solution

  • You are trying to use the map.panTo method before the map is initialized.

    This causes the initialize function to run when the page fires its "load" event (the complete DOM/page has been rendered):

    google.maps.event.addDomListener(window, 'load', initialize);
    

    This executes immediately, before the "load" event fires and the map variable is initialized:

    map.panTo(new google.maps.LatLng(37.4569, -122.1569));
    

    So it doesn't do anything. You should move it into your initialize function after the map is initialized.

    var map;
    
    function initialize() {
    
    var myOptions = {
          center : new google.maps.LatLng(34.053228, -118.259583),
          zoom   : 11,
          zoomControl: true,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    map.panTo(new google.maps.LatLng(37.4569, -122.1569));    
    };
    
    google.maps.event.addDomListener(window, 'load', initialize);