9

I have a dataset which already contains geojson. I can add it to my map with the following line of code.

L.geoJson(data.geojson).addTo(map);

And I get this geojson plotted on map

But I want to achieve this, where the surrounding area is covered up and my geojson shape is a hole in the middle of it.

geojson as a hole in the map

According to the leaflet documentation

You can also create a polygon with holes by passing an array of arrays of latlngs, with the first latlngs array representing the exterior ring while the remaining represent the holes inside.

So in theory something like:

var scotland = [[60,-13],[60,0],[50,4],[50,-13]];
L.Polygon([scotland,coordinatesOfShapeHole].addTo(map);

My problem is this function doesn't seem to like me passing in data.geojson or data.geojson.coordinates as the second parameter (coordinatesOfShapeHole);

Is there some way to convert data.geojson into a format the L.Polygon function is happy with?

Or alternatively do the same thing but with L.geoJson?

1 Answer 1

7

This should work. Which version of Leaflet are you using?

Here, have a look at this jsFiddle.

It is important you get the arrays right.

First array is the polygon object [ in here the outer ring [ in here some [lat,lon],[,] close the outer ring], then the inner ring [ in here some [lat,lon],[,] close the inner ring ] close the polygon ].

scotland = L.polygon([[[60,-13],[60,0],[50,4],[50,-13]],
                  [[55.7,-4.5],[56,-4.5],[56,-4],[55.7,-4]]]);
scotland.addTo(map);
3
  • 1
    Hi thanks. That works great if I'm dealing with a straightforward polygon, but my data is in geojson format. Do you know if there's a way to convert the geojson into polygon coordinates. Or achieve it using L.geoJson?
    – elMarquis
    Jun 15, 2015 at 14:08
  • That shouldn't be a problem. I forked the jsFiddle to use L.geoJson. jsfiddle.net/goldrydigital/xa6vg5zj Jun 15, 2015 at 19:23
  • Brilliant thanks. I hadn't realised the geojson contained a polygon definition which can be passed a multi-array similar to the standard polygon.
    – elMarquis
    Jun 15, 2015 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.