【问题标题】:Dropping marker on event, in google maps在事件中放置标记,在谷歌地图中
【发布时间】:2014-01-22 21:08:06
【问题描述】:

我正在尝试隐藏标记,直到点击地图。

如果我删除监听器,标记就在它应该在的位置,并且一切正常,当我添加它时,标记将永久消失。

我浏览了 google api 和几个网站(包括这个),我的室友甚至看过它,但我似乎无法让它工作。

我的理解是,在这种情况下,“点击”是谷歌特有的事情,因为浏览器处理类似事件的方式略有不同,所以也许监听器是问题所在。

非常感谢任何帮助。

var myCenter=new google.maps.LatLng(55.680313, 12.548468);

function initialize()
{
var mapProp = {

     center:myCenter,
     zoom:15,
     mapTypeId:google.maps.MapTypeId.ROADMAP
     };

var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);

google.maps.event.addListener(map, 'rightclick', function(event) {

     var marker=new google.maps.Marker({

          position:myCenter,
          animation:google.maps.Animation.DROP

          });
});

marker.setMap(map);
}

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

【问题讨论】:

    标签: javascript api google-maps google-maps-api-3


    【解决方案1】:

    我收到一个 javascript 错误:

    Uncaught ReferenceError: marker is not defined 
    

    在这一行:

    marker.setMap(map);
    

    变化:

    google.maps.event.addListener(map, 'rightclick', function(event) {
         var marker=new google.maps.Marker({
    
              position:myCenter,
              animation:google.maps.Animation.DROP
    
              });
    });
    
    marker.setMap(map);
    

    收件人:

    google.maps.event.addListener(map, 'rightclick', function(event) {
         var marker=new google.maps.Marker({
              position:myCenter,
              animation:google.maps.Animation.DROP
              });
         marker.setMap(map);
    });
    

    或者:

    google.maps.event.addListener(map, 'rightclick', function(event) {
         var marker=new google.maps.Marker({
              map: map,  
              position:myCenter,
              animation:google.maps.Animation.DROP
              });
    });
    

    working example

    【讨论】:

    • 我不敢相信我错过了这么久!现在完美运行! tyvm
    • 如果这回答了您的问题,请accept it(或至少投票...)
    • 赞成,因为它使用地图事件监听器,而不是 DOM 事件监听器。我们不应该混合使用 map api 和 dom api。
    【解决方案2】:

    为什么不将事件绑定到地图容器?

    document.getElementById("googleMap").onmousedown = function(e) {
        if ((e.which && e.which == 3) || (e.button && e.button == 2)) {
            var marker=new google.maps.Marker({
                position:myCenter,
                animation:google.maps.Animation.DROP
            });
            document.getElementById("googleMap").onmousedown = undefined;
        }
    }
    

    我们将onclick 设置为undefined 以禁用第一次点击后创建标记。

    UPD:对不起。注意,您要绑定右键单击。更新了代码。

    【讨论】:

    • 我最终使用了 geocodezips 解决方案,因为它只需要我更改一行,但我尝试这样做只是因为它也很好地工作。谢谢
    猜你喜欢
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多