2017-06-02 57 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/