2009-09-07 265 views
0

我目前加載與以下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); 

後來,我想其他標記添加到地圖中,用戶輸入後(緯度,經度)對我如何可以訪問我的功能initialize創建map變量?

回答

1

只是初始化地圖變量初始化函數之外:

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

儘管使用了全局變量,但它是封裝'map'的更好方法,例如在模塊模式中。 – 2010-04-21 11:36:36

1

從來沒有使用谷歌地圖,但嘗試創建全局,並把它傳遞到初始化要使用它每一次。

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

上述可能不會工作第一次,但希望你的想法。 – madphp 2009-09-07 13:05:25

+1

這是正確的想法,但是在加載頁面之前,您無法真正實例化地圖對象 - 您需要在初始化函數中執行此操作。 – 2009-09-07 17:55:31