Google Maps OverlayView:只允许SVG点击

时间:2018-05-14 09:25:26

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

我有一个包含多个SVG叠加层的Google地图。但是当我在这些SVG上添加点击事件时,所有叠加都是可点击的,我希望它只适用于SVG路径。

这是一个小提琴 https://jsfiddle.net/gmkfhr9s/1/

我使用自定义叠加文档作为基础 https://developers.google.com/maps/documentation/javascript/customoverlays

USGSOverlay.prototype.onAdd = function() {
  var div = document.createElement('div');
  div.style.borderStyle = 'dotted';
  div.style.borderWidth = '2px';
  div.style.borderColor = 'white';
  div.style.position = 'absolute';

  // Create the img element and attach it to the div.
  var img = document.createElement('img');
  img.src = this.image_;
  img.style.width = '100%';
  img.style.height = '100%';
  img.style.position = 'absolute';
  div.appendChild(img);

  this.div_ = div;

  // Add the element to the "overlayLayer" pane.
  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);

  //add element to clickable layer
  this.getPanes().overlayMouseTarget.appendChild(div);

  google.maps.event.addDomListener(img, 'mouseover', function() {
    img.style.opacity = '0.5';
  });
  google.maps.event.addDomListener(img, 'mouseout', function() {
    img.style.opacity = '1';
  });
};

您可以看到,使用鼠标悬停事件,所有叠加(有边框)都被选中并且只有SVG。

是否可以仅使SVG可点击?

如果这可以帮助您,则thread就是一个类似的问题。

编辑:

@ Sphinxxx的答案很有效。

我只想补充一点,如果你有多个SVG,其中一些SVG高于其他SVG,你必须添加这个CSS才能点击它们。

svg {
  pointer-events: none;
}
path {
  pointer-events: all;
}

1 个答案:

答案 0 :(得分:1)

首先,要控制SVG的内部<path>,您需要SVG元素本身,您无法通过带有外部SVG网址的图像访问它们。

获得SVG元素(最简单的方法是在HTML中包含SVG标记)后,本文就如何将该SVG用作地图叠加层提供了一个很好的示例:http://serversideguy.com/2017/10/31/how-do-i-place-svgs-on-a-google-map-using-custom-overlays/

我在这里做了一个完整的例子:https://codepen.io/Sphinxxxx/pen/wjEyMm

/**
    Will be called when the map is ready for the overlay to be attached.
*/
onAdd() {
    const svg = this.svg;
    svg.style.position = 'absolute';

    //Add the SVG element to a map pane/layer that is able to receive mouse events:
    const panes = super.getPanes();
    panes.overlayMouseTarget.appendChild(svg);
}

/**
    Whenever we need to (re)draw the overlay on the map, including when first added.
*/
draw() {
    //Here, we need to find the correct on-screen position for our image.
    //To achieve that, we simply ask the map's projection to calculate viewport pixels from the image's lat/lng bounds:
    const projection = super.getProjection(),
          bounds = this.bounds,
          sw = projection.fromLatLngToDivPixel(bounds.getSouthWest()),
          ne = projection.fromLatLngToDivPixel(bounds.getNorthEast());

    //Place/resize the SVG element:
    const s = this.svg.style;
    s.left = sw.x + 'px';
    s.top  = ne.y + 'px';
    s.width  = (ne.x - sw.x) + 'px';
    s.height = (sw.y - ne.y) + 'px';
}