如何在传单中设置geoJSON FeatureCollection的样式?

时间:2019-05-23 14:39:58

标签: javascript css leaflet geojson

我正在尝试使用L.geoJSON为geoJSON FeatureCollection设置样式,但是在偏离默认样式方面一直没有成功。

我已经尝试过L.geoJSON的文档(请参见下文),并将样式属性直接放入geoJSON功能中。这两个选项都不会影响图层的显示

//coordinates on map
var map = L.map('map').setView([29.76, -95.37], 10);
L.esri.basemapLayer('Gray').addTo(map);
var fromProjection = "+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378137 +b=6378137 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs";
var toProjection = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ";
var myStyle = {
    "color": "#ff7800",
    "weight": 5,
    "opacity": 0.65
};
var myLayer = L.geoJSON(watersheds,{
                coordsToLatLng: function (p) {
                    p = proj4(fromProjection,toProjection,p);  // reproject each point
                    p = [p[1],p[0]]    // swap the values
                    return p;          // return the lat/lng pair
                }},{
                style: myStyle
}).addTo(map);

预期结果:我的图层将变为橙色且略微透明

实际结果:我的图层是默认的蓝色

(类似于此:http://bl.ocks.org/andrew-reid/e472886c83819e8459178a4a56548449

2 个答案:

答案 0 :(得分:0)

尝试一下:

//coordinates on map
    var map = L.map('map').setView([29.76, -95.37], 10);
    L.esri.basemapLayer('Gray').addTo(map);
    var fromProjection = "+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378137 +b=6378137 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs";
    var toProjection = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ";
    var myStyle = {
        "color": "#ff7800",
        "weight": 5,
        "opacity": 0.65
    };
    myLayer = L.geoJson(watersheds, {
       onEachFeature: function (feature, layer) {
       layer.setStyle(feature.myStyle);

       }
    }).addTo(map);

答案 1 :(得分:0)

我发现了问题。

关于这一点的文档并不多,但是L.geoJSON的第二个参数是'options'。在coordsToLatLong之后,我无意间结束了争论。这种情况的正确代码粘贴在下面。

var map = L.map('map').setView([29.76, -95.37], 10);
    L.esri.basemapLayer('Gray').addTo(map);
    var fromProjection = "+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378137 +b=6378137 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs";
    var toProjection = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ";
    var myStyle = {
        "color": "#ff7800",
        "weight": 5,
        "opacity": 0.65
    };
    var myLayer = L.geoJSON(watersheds,{
                    style: myStyle,
                    coordsToLatLng: function (p) {
                        p = proj4(fromProjection,toProjection,p);  // reproject each point
                        p = [p[1],p[0]]    // swap the values
                        return p;          // return the lat/lng pair
                    }}).addTo(map);

您可以使用console.log(myLayer.options)检查您的答案