2017-06-02 5 views
0

ich bin benutzerdefinierte Marker in Google Map API hinzufügen. als gegeben können wir diese Funktion addmarker() innerhalb initialisieren() ich möchte es außerhalb nennen. In einer anderen Funktion.Wie google map addmarker Funktion außerhalb der Funktion initialize() aufrufen?

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*/

Anregungen sind willkommen fühlen Sie sich frei, die Frage (Bit Woche in Englisch) zu bearbeiten. Danke.

Antwort

0

müssen Sie

var map 

Dann eine globale Variable einstellen können Sie die Karte Referenz überall verwenden:

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/

Verwandte Themen