我在谷歌地图api中添加自定义标记。 作为给定我们可以在initialize()中调用该函数addmarker() 我想在外面打电话。在另一个功能。
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
center: chaina,
zoom: 13,
mapTypeControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT,
}
});
google.maps.event.addListener(map, 'click', function(evnt) {
addMarker(event.latLng, map);
});
}
/*i want to call inside this drp function*/
function drp(event){
google.maps.event.addListener(map, 'click', function(evnt) {
addMarker(event.latLng, map);
});
}
/*I need marker to be added on clicked position*/
答案 0 :(得分:2)
您需要设置全局变量
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
});
}
JSFIDDLE :https://jsfiddle.net/vy9seg3b/1/