Search code examples
leafletstylesgeojsonmarkers

Displaying styles stored in a GeoJson File and making lines appear as lines instead of markers


I've been trying to get Leaflet to display a geojson file using the styles described in the geojson file, and I can't get it to work. The geojson below shows that I've got styles in there - OGR style pen etc, but I've tried extracting them using style function(styles) {return {colour : data.properties.pen}}, but it gives me an error on the console - but not enough errors to match the number of layers - so I can understand that some layers may not have a "pen" property, but none of the layers are coming up with the any differences.

"features": [ { "type": "Feature", "properties": { "Layer": "Buildings", "SubClasses": "AcDbEntity:AcDb2dPolyline", "EntityHandle": "2ABF", "OGR_STYLE": "PEN(c:#ff7f00,p:"1.2g 0.72g 0.12g 0.72g")" }, "geometry": { "type": "LineString", "coordinates": [ [ -1.386274792183286, 54.907452998026585, 0.0 ], [ -1.386201193400163,

In fact, as the above geojson shows, it's actually a geometry - but all that's showing up is a marker, which is my second problem. Can anyone point me to some example codes or anything which may help me?

                $.getJSON(address, function(data) {
                //add GeoJSON layer to the map once the file is loaded
                layer[i] = L.geoJson(data, {style: function(styles) {
                                              return {color: data.properties.pen,
                                                      weight: data.properites.weight
                                                    };
                                              onEachFeature: onEachFeature
                                                                      }
                                            }).addTo(map);

Thanks.


Solution

  • Change your code to:

    function onEachFeature(feature, layer) {
        if (feature.properties && layer instanceof L.Path) {
            layer.setStyle({
                color: feature.properties.pen,
                weight: feature.properites.weight
            });
        }
    }
    
    
    $.getJSON(address, function(data) {
        //add GeoJSON layer to the map once the file is loaded
        layer[i] = L.geoJson(data, {
            onEachFeature: onEachFeature
        }).addTo(map);
    });
    
    

    Leaflet GeoJson Tutorial