在MapBox中设计geoJSON特征层的样式

Styling a geoJSON Feature Layer in MapBox

本文关键字:特征 样式 geoJSON MapBox      更新时间:2023-09-26

我刚开始玩MapBox,遇到了一个令人困惑的问题。我正在使用以下代码创建一个带有geoJSON层的地图:

var map = L.mapbox.map('map', '<MapBoxID>');
            var zipLayer = L.mapbox.featureLayer('data/blah.json');
            zipLayer.addTo(map);
            zipLayer.setStyle({color: 'red'});

地图显示并显示了geoJSON,但它忽略了样式。不过,当我在浏览器中将最后一行复制到JS控制台时,它运行得很好。

我在这里错过了什么?此外,我已经尝试了至少十几种不同的方法,将样式直接包含在featureLayer()调用中的选项中,但都没有成功。创建要素图层时如何指定样式?

我在这里猜测了一点,因为我对Mapbox JS不是很了解,但它听起来很像一个异步错误。奇怪的是,我在Mapbox或传单API中没有看到任何关于该函数回调的内容。但是,您可以直接将GeoJSON传递给featureLayer(),因此我建议使用jQuery(或您选择的XHR库)来获取数据:

var map = L.mapbox.map('map', '<MapBoxID>');
var zipLayer;
$.getJSON('data/blah.json', function(data) {
    zipLayer = L.mapbox.featureLayer(data);
    zipLayer.addTo(map);
    zipLayer.setStyle({color: 'red'});
});

希望这能奏效。

我会使用内置的featureLayer函数,然后等待它准备好。这应该有助于让你指向正确的方向:

var featureLayer = L.mapbox.featureLayer()
    .loadURL('/example-single.geojson')
    .on('ready', function(layer) {
        this.eachLayer(function(marker) {
            // See the following for styling hints:
            // https://help.github.com/articles/mapping-geojson-files-on-github#styling-features
            marker.setIcon(L.mapbox.marker.icon({
                'marker-color': '#CC0000'
            }));
        });
    })
    .addTo(map);

您在设置样式后是否尝试添加zipLayer?