javascriptleafletpolygonleaflet-draw

Leaflet draw polygon on load map


I have this polygon coordinates

let polygon = [
    [
        51.40545845031738,
        35.706447104954194
    ],
    [
        51.390438079833984,
        35.70568044469603
    ],
    [
        51.38288497924805,
        35.69689817401091
    ]
]

I want to be polygon drawn when map load. Also editable.

in the other words

How to show editable polygons on map after map loading.


Solution

  • This solved for me in this way

    let polygon = [
        [
            51.40545845031738,
            35.706447104954194
        ],
        [
            51.390438079833984,
            35.70568044469603
        ],
        [
            51.38288497924805,
            35.69689817401091
        ]
    ];
    
    let geojson = {
        "type": "FeatureCollection",
        "features": [{
            "type": "Feature",
            "properties": {},
            "geometry": {
                "type": "Polygon",
                "coordinates": []
            }
        }]
    };
    let arr = [];
    polygon.forEach(function (item, index) {
        arr.push([item[1], item[0]]);
    });
    geojson.features[0].geometry.coordinates.push(arr);
    
    var drawnItems = new L.FeatureGroup();
    var geoJsonGroup = L.geoJson(geojson).addTo(map);
    addNonGroupLayers(geoJsonGroup, drawnItems);
    
    // Would benefit from https://github.com/Leaflet/Leaflet/issues/4461
    function addNonGroupLayers(sourceLayer, targetGroup) {
        if (sourceLayer instanceof L.LayerGroup) {
            sourceLayer.eachLayer(function (layer) {
                addNonGroupLayers(layer, targetGroup);
            });
        } else {
            targetGroup.addLayer(sourceLayer);
        }
    }