1

I am pretty new in working with Leaflet js and I have a polygon

var coords = layer.getLatLngs();
L.polygon(coords, { fillColor: 'red', fillOpacity: 0.5, weight: 20, color: 'red', opacity: 0.5, fill: true}).addTo(map);

and I need to add another polygon around it with an offset. I've tried using leaflet.polylineoffset, first with polyline

coords.push(coords[0]);
L.polyline(coords, { color: 'purple', weight: 2, opacity: 0.7, fill: false, offset: 10}).addTo(map);

but it didn't close properly

enter image description here

Then, by using polygon,

L.polygon(coords, { color: 'purple', weight: 2, opacity: 0.7, fill: false, offset: 10, polygon: true }).addTo(map);

it draws one of the line on top of the other polygon

enter image description here

Is there a way to add a polygon around an existing one with an offset?

6
  • What should be the offset unit: meters or pixels?
    – TomazicM
    Jun 22, 2022 at 14:38
  • @TomazicM both are good
    – LAffair
    Jun 22, 2022 at 14:41
  • But completely different in behavior. Pixel offset stays the same regardless of zoom, offset in meters visually changes with zoom.
    – TomazicM
    Jun 22, 2022 at 15:10
  • @TomazicM For the red polygon I'm changing the stroke weight when the zoom changes (to keep the size in meters) and I think meters would be best in this case
    – LAffair
    Jun 22, 2022 at 15:13
  • This is a "turfjs buffer" problem. Jun 22, 2022 at 15:48

1 Answer 1

0

One possible way to solve this is to actually use Leaflet.PolylineOffset plugin, with slight modification of plugin code (only one line):

.
.
.
joinLineSegments: function(segments, offset) {
    var joinedPoints = [];
    var first = segments[0];
    var last = segments[segments.length - 1];

    if (first && last) {
        joinedPoints.push(first.offset[0]);
        forEachPair(segments, L.bind(function(s1, s2) {
            joinedPoints = joinedPoints.concat(this.joinSegments(s1, s2, offset));
        }, this));
        joinedPoints = joinedPoints.concat(this.joinSegments(last, first, offset));  // added line
//      joinedPoints.push(last.offset[1]);   // removed line
    }

    return joinedPoints;
},
.
.
.

Example after this modification:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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