简体   繁体   English

使用Google Maps API v3添加多个标记

[英]Add multiple markers with Google Maps API v3

I have the following function to add one single marker but I want to add multiple markers by clicking on the map. 我有以下功能来添加一个标记,但我想通过点击地图添加多个标记。 I have Googled but I can't get any straight answer on how I can solve this problem. 我用谷歌搜索但我无法得到任何关于如何解决这个问题的直接答案。

function placeMarker(location) {
    if(marker) {
        marker.setPosition(location);
    } else {
        marker = new google.maps.Marker({
            position: location,
            map: gm_map,
            draggable: true
        });
    }
}

I know I need to use Array() but I don't know exactly how. 我知道我需要使用Array()但我不确切知道如何。 How can I solve my problem? 我怎样才能解决我的问题?

DEMO : removed because the problem has been solved. DEMO :删除因为问题已经解决了。

Do you need to use the marker variable outside of the placeMarker function? 你需要在placeMarker函数之外使用marker变量吗? Your function is not deleting the marker, it is checking to see if the marker variable exists and moves the marker using the setPosition function. 您的功能不是删除标记,而是检查标记变量是否存在并使用setPosition函数移动标记。 You need to remove that line if you want multiple markers to exist. 如果要存在多个标记,则需要删除该行。

function placeMarker(location) {
   //marker variable will only exist inside this function
   var marker = new google.maps.Marker({
       position: location,
       map: gm_map,
       draggable: true
   });        
}

Here is an example: http://jsfiddle.net/bryan_weaver/aEyfW/ 这是一个例子: http//jsfiddle.net/bryan_weaver/aEyfW/

Ok, you need to have an event listener for the 'click' event on the map. 好的,您需要在地图上为“click”事件提供事件监听器。 And this needs to pass the currently-clicked location to your placeMarker function. 这需要将当前单击的位置传递给您的placeMarker函数。 Try this (add this event listener in the same place where you initialise your map) 试试这个(在初始化地图的同一个地方添加此事件监听器)

google.maps.event.addListener(gm_map, 'click', function(event) {
      placeMarker(event.latLng);
});

And modify your placeMarker function, so instead of having one global variable marker which you update with each click, create a new marker each time: 并修改您的placeMarker函数,因此您不必每次单击都更新一个全局变量标记,而是每次都创建一个新标记:

function placeMarker(location) {
    var marker = new google.maps.Marker({
            position: location,
            map: gm_map,
            draggable: true
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM