Google Maps OverlayView: сделать клик только по SVG - PullRequest
0 голосов
/ 14 мая 2018

У меня есть карта Google с несколькими наложениями SVG.Но когда я добавляю событие щелчка для этих SVG, все наложения активируются щелчком, и я хочу, чтобы оно работало только для пути SVG.

Вот скрипка https://jsfiddle.net/gmkfhr9s/1/

Я используюдокументация Custom overlays в качестве основы 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';
  });
};

Вы можете видеть, что с событием mouseover все оверлей (рамка с рамкой) выбрана и только SVG.

Возможно ли сделать только SVG кликабельным?

Эта нить является аналогичной проблемой, если вам это поможет.


РЕДАКТИРОВАТЬ:

@ Ответ Sphinxxx работает хорошо.

Я просто хочу добавить, что если у вас есть несколько SVG с некоторыми из них выше других, вам придетсядобавьте этот CSS, чтобы иметь возможность нажимать на них.

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

1 Ответ

0 голосов
/ 15 мая 2018

Прежде всего, для управления внутренними <path> SVG вам нужен сам элемент SVG, вы не можете получить к ним доступ через изображение с внешним URL-адресом SVG.

Как только у вас есть элемент SVG(проще всего включить разметку SVG в ваш HTML), в этой статье представлен хороший пример того, как использовать этот 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';
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...