简体   繁体   中英

How do I change the style of a geoJSON layer of LineStrings in Leaflet 1.0.3

I am trying to change the style of a layer of lines strings in leaflet 1.0.3. My layer is a geoJSON layer generated using an ajax call and the leaflet-ajax lib. I can see my layer on the map, but it inherits the default styling, not the styling I am trying to add.

var lines = new L.GeoJSON.AJAX('/rest/lines');

lines.setStyle({color:"#00000",weight:10}).addTo(map);

var overlays = {"Lines": lines};

L.control.layers(overlays).addTo(map);

You should try to define a function which will style each line as it is loaded up into Leaflet.

From this link: https://github.com/Dominique92/Leaflet.GeoJSON.Ajax

...
new L.GeoJSON.Ajax(
    <URL>, // GeoJson server URL.
    {
        argsGeoJSON: {
            name: value, // GeoJson args pairs that will be added to the url with the syntax: ?name=value&...
            ...
        }
        bbox: <boolean>, // Optional: whether or not add bbox arg to the geoJson server URL
        style: function(feature) { // Optional
            return {
                "<NAME>": <VALUE>, // Properties pairs that will overwrite the geoJson flow features properties
                "<NAME>": feature.properties.<NAME>, // The value can be calculated from any geoJson property for each features.
                ...
            };
        }
    }
).addTo(map);
...

This is my code, which is for shapes not lines, but it should work in a similar way:

geojson = L.geoJson(myGeoJson.features, {
    onEachFeature: onEachFeature,
    style: styleFeature,
}).addTo(myLeafletMap);

and then I have the functions:

function onEachFeature(feature, layer) {
...
}

and

function styleFeature(feature){
    return {
        weight: 2.5,
        opacity: 1,
        color: getColour('blue'),
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM