如何在Leaflet 1.0.3中更改LineStrings的geoJSON图层的样式

时间:2017-03-09 16:14:31

标签: javascript leaflet

我正在尝试更改传单1.0.3中的一行线条字符串的样式。我的图层是使用ajax调用和leaflet-ajax lib生成的geoJSON图层。我可以在地图上看到我的图层,但它继承了默认样式,而不是我想要添加的样式。

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);

1 个答案:

答案 0 :(得分:2)

你应该尝试定义一个函数,它会在每行加载到Leaflet时为每一行设置样式。

从此链接: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);
...

这是我的代码,用于形状而不是线条,但它应该以类似的方式工作:

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

然后我有功能:

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

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