polygon – Adding a Polygon with Offset Around Another Polygon in Leaflet JS

leafletpolygon

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?

Best Answer

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