Google Maps OverlayView: make only SVG clickable

前端 未结 1 1651
借酒劲吻你
借酒劲吻你 2021-01-14 16:15

I have a Google Map with multiple SVG overlays. But when I add a click event on these SVG, all the overlay is clickable and I want it to work only for the SVG path.

相关标签:
1条回答
  • 2021-01-14 16:25

    First of all, to control the SVG's inner <path>s you need the SVG element itself, you can't access them through an image with an external SVG url.

    Once you have your SVG element (the easiest is to include the SVG markup in your HTML), this article has a good example on how to use that SVG as a map overlay: http://serversideguy.com/2017/10/31/how-do-i-place-svgs-on-a-google-map-using-custom-overlays/

    I have made a complete example here: 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';
    }
    
    0 讨论(0)
提交回复
热议问题