Markers not showing on google maps

假装没事ソ 提交于 2021-02-10 06:13:31

问题


I'm trying to show markers on my map. but it's not showing them.

this is the code I use:

var map;
var markers = new Array();

function initialize() {
    var mapOptions = {
        zoom: 12,
        center: new google.maps.LatLng(27.9881, 86.9253),
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    google.maps.event.addListener(map, 'click', addMarker);
}

function addMarker(event) {
    markers.push(event.latLng);

    marker = new google.maps.Marker({
        position: event.latLng,
        map: map
    });

    console.log(markers);
}

google.maps.event.addDomListener(window, 'load', initialize);

the console is logging on every click an new coordinate, so the function is called, and coordinates are passed. And I can't really see any problems in the marker code.

So can anyone see the problem?


回答1:


map is a local variable, only visible inside initialize.

Use this instead of map when you set the map-property of the marker:

function addMarker(event) {
    markers.push(event.latLng);

    marker = new google.maps.Marker({
        position: event.latLng,
        map: this
    });
}

Explanation:

the callback will be executed in the scope of the object that triggers the event. Here it is the Maps-instance(because the click-listener has been applied to the map ), this will refer to this object inside the callback.




回答2:


markers.push(event.latLng);

Here you're pushing the latlng, not the marker.

markers is an array variable with global scope, whereas marker is a local variable.
In markers array you have to insert each inidividual marker and then process it.

function addMarker(event) {
    var marker = new google.maps.Marker({
        position: event.latLng,
        map: map
    });
    markers.push(marker);
}


来源:https://stackoverflow.com/questions/20679730/markers-not-showing-on-google-maps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!