【问题标题】:Google Map API - Map click event not fired under Polygon, Circle, Rectangle?Google Map API - 在多边形、圆形、矩形下未触发地图点击事件?
【发布时间】:2022-01-09 01:19:36
【问题描述】:

在 Google 地图 API 中, 当监听来自 Map 对象的点击事件时, 单击多边形、圆形、矩形时不会触发该事件。

如何将点击事件冒泡到 Map 对象?

  const circle = new google.maps.Circle({
    center,
    radius,
    map,
  });

  // This event will not fire when clicking the circle
  map.addListener("click", (e) => {
    console.log('map click');
  })

示例: https://jsfiddle.net/rphsf32e/14/
单击地图将添加一个标记。但是,如果点击是在圆圈上方,则点击事件不会从地图中触发。仅来自圈子。

【问题讨论】:

    标签: google-maps-api-3 click event-bubbling


    【解决方案1】:

    最简单的解决方案是让圆形(和多边形/矩形)“不可点击”,在构造函数中设置属性:clickable: false

    const circle = new google.maps.Circle({
      center: myLatlng,
      radius: 100000,
      map,
      clickable: false
    })
    

    proof of concept fiddle

    代码 sn-p:

    function initMap() {
      const myLatlng = { lat: -25.363, lng: 131.044 };
      const map = new google.maps.Map(document.getElementById("map"), {
        zoom: 7,
        center: myLatlng,
      });
      
      const circle = new google.maps.Circle({
        center: myLatlng,
        radius: 100000,
        map,
        clickable: false
      })
      
      circle.addListener("click", (e) => {
        alert('inside circle');
        console.log(e)
      });
    
      map.addListener("click", (e) => {
        new google.maps.Marker({
            position: e.latLng,
            map,
            title: `${ e.latLng.lat() }, ${ e.latLng.lng() }`,
        });
      })
    }
    /* 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 Click Events</title>
        <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
        <!-- jsFiddle will insert css and js -->
      </head>
      <body>
        <div id="map"></div>
        <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
        <script
          src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"
          async
        ></script>
      </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多