2017-06-02 63 views
0

我在谷歌地圖API中添加自定義標記。 作爲它的給定,我們可以在initialize() 內調用addmarker()函數,我想在外面調用它。在另一個功能。如何在initialize()函數外調用google map addmarker函數?

function initialize() { 
 
map = new google.maps.Map(document.getElementById('map'), { 
 
     \t center: chaina, 
 
     \t zoom: 13,  \t 
 
     \t mapTypeControlOptions: { 
 
\t \t  position: google.maps.ControlPosition.TOP_RIGHT, 
 
\t \t } 
 
    }); 
 

 
google.maps.event.addListener(map, 'click', function(evnt) { 
 
     \t addMarker(event.latLng, map); 
 
     \t 
 
    }); 
 
} 
 

 
/*i want to call inside this drp function*/ 
 
function drp(event){ 
 
\t google.maps.event.addListener(map, 'click', function(evnt) { 
 
     \t addMarker(event.latLng, map); 
 
     \t 
 
    }); 
 
} 
 
/*I need marker to be added on clicked position*/

任何建議,歡迎隨時編輯的問題(位本週英文)。 謝謝。

回答

0

你需要設置一個全局變量

var map 

然後你就可以在任何地方使用的地圖參考:

var map; //global variable to be access anywhere 

function initMap() { 
    map = new google.maps.Map(document.getElementById('map'), { 
    center: { 
     lat: -34.397, 
     lng: 150.644 
    }, 
    zoom: 8 
    }); 

    //add the listener to the map within the initMap 
    google.maps.event.addListener(map, 'click', function(event) { 
    placeMarker(event.latLng); 
    }); 

} 

//this function is calle when the button is clicked which calls the placemarker function outside the init 
function addMarker(){ 
     placeMarker({lat: -34.397, lng: 150.644}); 
} 


//this can now be called from anywhere 
function placeMarker(location) { 
    var marker = new google.maps.Marker({ 
    position: location, 
    map: map 
    }); 
} 

的jsfiddlehttps://jsfiddle.net/vy9seg3b/1/