[GIS] How to convert geojson to polygon in Leaflet

geojsonjavascriptleaflet

I have this json data:

var states = [{
    "type": "Feature",
    "properties": {"party": "Republican"},
    "geometry": {
        "type": "Polygon",
        "coordinates": [[
            [-104.05, 48.99],
            [-97.22,  48.98],
            [-96.58,  45.94],
            [-104.03, 45.94],
            [-104.05, 48.99]
        ]]
    }
}
}];

It'is easy to visualize this on leaflet map by doing this:

L.geoJSON(states, {
    style: function(feature) {
        switch (feature.properties.party) {
            case 'Republican': return {color: "#ff0000"};
        }
    }
}).addTo(map);

But i need the "type" of states is "polygon" not "geojson", so the result will be like this:

var states_polygon = L.polygon([[
            [48.99,-104.05],
            [48.98,-97.22],
            [45.94,-96.58],
            [45.94,-104.03],
            [48.99,-104.05]
        ]]).addTo(map);

I knew that both variable will be give the same visual on leaflet map but all i need is the object type of that variable as polygon.. How can i do this?

Best Answer

Instead of reading the GeoJSON straight forward, you can use a .forEach js function to map every geometry, like this:

// your json var: states
states.forEach(function(state) {
    var polygon = L.polygon(state.geometry.coordinates, {
        weight: 1,
        fillOpacity: 0.7,
        color: 'white',
        dashArray: '3'
    }).addTo(map);
});