2009-09-07 14 views
0

Je suis en train de charger une carte avec le javascript suivant.Marqueurs dans google maps

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); 

Plus tard, je veux ajouter d'autres marqueurs à la carte, après que l'utilisateur a entré un (lat, lon) paire Comment puis-je accéder à la variable map que j'ai créé dans la fonction initialize?

Répondre

1

initialiser juste la variable carte en dehors de la fonction initialize:

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. 
+0

Malgré l'utilisation de variables globales, c'est un meilleur moyen d'encapsuler 'map', par ex. dans un modèle de module. –

1

Vous n'avez jamais utilisé Google Maps, mais essayez de le créer globalement et passez-le à l'initialisation chaque fois que vous souhaitez l'utiliser.

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)); 
+0

ci-dessus fonctionne probablement pas première fois, mais nous espérons que vous avez l'idée. – madphp

+1

C'est la bonne idée, mais vous ne pouvez pas réellement instancier l'objet carte jusqu'à ce que la page soit chargée - vous devez le faire dans la fonction initialize. –

Questions connexes