views:

1280

answers:

2

I'm currently loading a map with the following javascript.

  google.load("maps", "2.x");

  // Call this function when the page has been loaded
  function initialize() {

    var map = new google.maps.Map2(document.getElementById("map"));
    map.setCenter(new google.maps.LatLng(52,-3), 13);

    var point = new google.maps.LatLng(52,-3);
    var marker = new google.maps.Marker(point, {draggable: true});


    map.addOverlay(marker);

    google.maps.Event.addListener(marker, "dragend", function(latlng) {
    marker.openInfoWindowHtml("Dragged to <br>" + latlng);
    });    
  }

google.setOnLoadCallback(initialize);

Later on, I want to add other markers to the map, after the user has input a (lat,lon) pair How can I access the map variable that I created in the function initialize?

+1  A: 

Never used Google Maps, but try creating it globally and pass it into initialize each time you want to use it.

google.load("maps", "2.x");

var map = new google.maps.Map2(document.getElementById("map"));

function initialize(map,lat,lon) {

    map.setCenter(new google.maps.LatLng(lat,lon), 13);

    var point = new google.maps.LatLng(lat,lon);
    var marker = new google.maps.Marker(point, {draggable: true});


    map.addOverlay(marker);

    google.maps.Event.addListener(marker, "dragend", function(latlng) {
    marker.openInfoWindowHtml("Dragged to <br>" + latlng);
    });

    return map
}

google.setOnLoadCallback(initialize(map,lat,lon));
madphp
the above probably wont work first time, but hopefully you get the idea.
madphp
This is the right idea, but you can't actually instantiate the map object until the page is loaded - you need to do that in the initialize function.
Chris B
A: 

Just initialize the map variable outside of the initialize function:

google.load("maps", "2.x");

var map;

// Call this function when the page has been loaded
function initialize() {

  map = new google.maps.Map2(document.getElementById("map"));
  map.setCenter(new google.maps.LatLng(52,-3), 13);

  var point = new google.maps.LatLng(52,-3);
  var marker = new google.maps.Marker(point, {draggable: true});

  map.addOverlay(marker);

  google.maps.Event.addListener(marker, "dragend", function(latlng) {
    marker.openInfoWindowHtml("Dragged to <br>" + latlng);
  });    
}

google.setOnLoadCallback(initialize);

//Now you can access the map variable anywhere in your code.
Chris B
Despite using global variables, it is a better way to encapsulate `map` e.g. in a module pattern.
Török Gábor