1

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.

Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144

1 Answers1

1

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);
    }
}
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
  • Doesn't your `arr` array simply end up being a copy of your `polygon` array? Seems like a redundant step doing the `forEach` / `push` loop. – peeebeee Jun 26 '19 at 10:32
  • I am using Angular 8! Have implemented "https://github.com/Asymmetrik/ngx-leaflet-draw". Everything is working fine. I am able to draw polygon but when I reload the page, I want that polygon (which was created last time) to be loaded from localStorage. – md_salm Dec 10 '19 at 10:00
  • I am trying to load the polygon from the component(ts file). I can sort that localStorage thing later. I am drawing the polygon and getting the value(Lat long) by consoling them from the component.. I want to give values from the component by ngOnInit() or leafletMapReady and polygon should be drew on initial load. – md_salm Dec 10 '19 at 10:18