Conner Leverett
Conner Leverett

Reputation: 593

Bring SVG to front of Leaflet

I'm trying to add an SVG element on top of my Leaflet map but it is hidden by the geoJSON markers as such: SVG under markers

This is the code I have so the SVG element is infront of the map

var svg = d3.select(this.map.getPanes().overlayPane).append('svg')
    .attr({
        "width": width,
        "height": height 
        })
    .on('click',function(){
        svg.remove();
});

I've tried this method but with no avail:

d3.selection.prototype.moveToFront = function(){
    return this.each(function(){
        this.parentNode.appendChild(this);
    });
};

svg.moveToFront();

I was thinking I might need to .hide() the markers underneath the SVG but wasn't sure if that was the right direction. Thank you!

Upvotes: 1

Views: 2394

Answers (2)

vahid
vahid

Reputation: 3

You can use L.DomUtil.toFront and L.DomUtil.toBack

Also you have to Use L.SVG layer with set pane to 'markerPane'

Upvotes: 0

Conner Leverett
Conner Leverett

Reputation: 593

If anyone ever stumbles upon this I found another solution to my issue.

If I used .popupPane() the SVG element would cover the markers like I wanted but it also oddly moved my buttons. What I did instead was add another <div> element to my html (id = "map-nav"). I then edited my CSS so my "map" div was relative, "map-nav" was absolute and when I added my SVG to my map appended it to "map-nav" not "map". Here is the code example:

HTML

<div id="map" style="height:100%; width:100%;margin: 0"> </div>
        <div id="map-nav"></div>
        <script type="text/javascript">

JavaScript

//Define d3 margin
var margin = {top: 20, right: 10, bottom: 100, left: 40},
    width = 700 - margin.right - margin.left,
    height = 100 - margin.top - margin.bottom;

svg = d3.select("#map-nav").append('svg')
        .attr({
            "width": 500,
            "height": 500, 
        })
        .on('click',function(){
            svg.remove();
        });

CSS

svg {
    position: absolute;
    background-color:white;
    margin-top:auto;
    margin-bottom:auto;
    margin-left:auto;
    margin-right: auto;
    display: block;
}
map {
    width: 100%;
    height: 300px;
    position: relative;
}
map-nav {
    position: absolute;
    left: 60px;
    top: 10px;
    width: 100px;
    height: 100px;
    z-index: 2;
}

Here is what it looks like now Hope that helps someone who may also struggle with this!

Upvotes: 1

Related Questions