user3601262
user3601262

Reputation: 681

Leaflet make PolyLine on top of geoJson

I need to create dashed line on top of the geoJson object, but this object always appearing on top.

I have tried to set z-index parameters both to the css-classes of objects and as parameters in the js code, but it doesn't help.

I also see that the line moved to the top of geoJson when I manually drag the line's tag below the countries tag, but I surely don't want to do it in the js code with jquery (seems like a very bad decision).

I'm creating the map using this code:

// Creating the map
var map = L.map('map').setView([25, 10], 4);

// Creating the polyline
var pointA = new L.LatLng(-20, -20);
var pointB = new L.LatLng(80, 77.70641);
var pointList = [pointA, pointB];

var firstpolyline = new L.Polyline(pointList, {
  smoothFactor: 1,
  className: 'my_polyline'
});
firstpolyline.addTo(map);


// Creating the geojson object
var geojson = {"type": "FeatureCollection","features": [{ "type": "Feature", "properties": { "NAME": "Custom country" }, "geometry": { "type": "Polygon", "coordinates": [ [ [-0.18,29.76],[8.79,31.65],[13.54,27.61],[8.53,21.86] ] ] } }]}

var myCustomStyle = {
  stroke: false,
  fill: true,
  fillColor: 'green',
  fillOpacity: 1
}

L.geoJson(geojson, {
  clickable: true,
  style: myCustomStyle
}).setZIndex(1).addTo(map);

And some CSS:

.my_polyline { 
 stroke: red;
  fill: none;
  stroke-dasharray: 10,10; 
  stroke-width: 2;  
}

You can also see working example on jsfiddle: https://jsfiddle.net/d7v4bhku/4/

Upvotes: 1

Views: 2430

Answers (1)

Remolten
Remolten

Reputation: 2682

The order you add them to the map matters. If you want the line on top, simply add it to the map after the geojson layer.

L.geoJson(geojson, {
  clickable: true,
  style: myCustomStyle
}).addTo(map);

var firstpolyline = new L.Polyline(pointList, {
  smoothFactor: 1,
  className: 'my_polyline'
});
firstpolyline.addTo(map);

Then, you get your desired result. Dashed Polyline on top of GeoJSON

Upvotes: 1

Related Questions