According to the official tutorial, I can load and show all polygons from a local geoJSON file now. I'm planning on clipping the newly created SVG layer using a custom outline path. I started with a circle as a child of clipPath that is created through Leaflet's L.circle to avoid the coordinate projection.The main code based on the official example is as follows:
// Create a circle outline
var clipcircle = new L.circle([34.5, -95.5], {radius: 300000, className: 'outline'}).addTo(map);
// Create <defs> and <clippath> elements using jquery
$('svg').prepend('<defs><clipPath id="myclip"></clipPath></defs>');
// Move the <path> element of clipcircle from <g> to <clipPath>
$('path.outline').appendTo('#myclip');
// Add CSS clip-path attribute to all svg groups
$('g').css('clip-path', 'url(#myclip)');
// load and show polygons from geoJSON
var geojson = L.geoJSON(statesData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
map.fitBounds(geojson.getBounds());
The code works as expected however the clipPath is not working. Only the area inner the circle is expected to be shown, but all polygons except the circle are still be shown on the page, illustrated as the following images:
add the circle without moving
The problem is that when creating the clipPath new element, jquery lowercases the element name as (stated in the specs) as html tags should not be case sensitive (but seems like the clipPath is indeed case sensitive)
To overcome this, you need to revert back to native DOM manipulation and select the svg and create the element with createElementNS:
var svg = document.getElementsByTagName('svg')[0]
//Create a new element of clipPath
var clipPathChild = document.createElementNS('http://www.w3.org/2000/svg', "clipPath");
//set an ID (I went lazy and continued with jquery)
$(clipPathChild).attr('id', 'myclip')
//append new node to the svg
svg.appendChild(clipPathChild);
//the "outline" class was added previously to the geojson we want to use as mask
// add the outline to clip the new node just created
$('path.outline').appendTo('#myclip');
//set the ID of the clip-path to the main feature to clip
$('path').attr('clip-path', 'url(#myclip)');
This solution worked for me, as your code is in theory correct, it fails due to that simple lowercase convertion of the jquery when creating a new element
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With