【问题标题】:click on map doesn't get triggered when the click is on a polygon单击多边形时不会触发单击地图
【发布时间】:2020-12-17 02:09:52
【问题描述】:

我有一个简单的谷歌地图,当我点击它时,我希望触发警报:

let map;

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
  
  const triangleCoords = [
    { lat: -34.397, lng: 150.644 },
    { lat: -33.5, lng: 152 },
    { lat: -34.4, lng: 149 },
  ];
  const triangle = new google.maps.Polygon({
     paths: triangleCoords,
  });
  triangle.setMap(map);
        
  google.maps.event.addListener(map, "click", (e) => {
  alert('there was a click')
  const result = google.maps.geometry.poly.containsLocation(
     e.latLng,
     triangle
  );
  
  if(result)alert('inside triangle')
  else alert('outside triangle')
});

}

fiddle

但是,当我单击多边形时,不会触发事件,也不会触发警报。在多边形之外它确实有效。

我做错了什么?

【问题讨论】:

  • 如果你删除triangle.setMap(map),这可行,但你不会有突出显示的区域。 setMap 可能正在创建所选区域的新地图,它会覆盖现有的事件侦听器。因此,您将不得不再次为此添加事件侦听器。您也可以检查 setMarker 而不是使用它。

标签: javascript google-maps polygon


【解决方案1】:

google.maps.Polygon 在“可点击”时捕获点击(默认为 true)。如果设置clickable:false,则map点击监听函数将运行。来自documentation

可点击可选
类型:布尔可选
指示此 Polygon 是否处理鼠标事件。默认为真。

相关问题:Cant GetPosition in Overlay Polygon Zone

(另一种选择是将Polygon 保留为clickable:true,但将相同的事件侦听器添加到Polygon

proof of concept fiddle

代码 sn-p:

let map;

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    center: {
      lat: -34.397,
      lng: 150.644
    },
    zoom: 8,
  });

  const triangleCoords = [{
      lat: -34.397,
      lng: 150.644
    },
    {
      lat: -33.5,
      lng: 152
    },
    {
      lat: -34.4,
      lng: 149
    },
  ];
  const triangle = new google.maps.Polygon({
    paths: triangleCoords,
    clickable: false
  });
  triangle.setMap(map);

  google.maps.event.addListener(map, "click", (e) => {
    alert('there was a click')
    const result = google.maps.geometry.poly.containsLocation(
      e.latLng,
      triangle
    );

    if (result) alert('inside triangle')
    else alert('outside triangle')
    /* console.log(result) */

  });

}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Simple Map</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>
</body>

</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2017-12-08
    • 2016-05-29
    • 1970-01-01
    • 2012-11-28
    相关资源
    最近更新 更多