代码之家  ›  专栏  ›  技术社区  ›  Mahanmeh

使用mapbox基于geojson定义多边形填充颜色

  •  4
  • Mahanmeh  · 技术社区  · 7 年前

    我使用mapbox示例在地图上创建多个多边形,每个多边形都有弹出事件。我的问题是,我需要根据每个多边形的geojson属性设置不同的填充颜色。

    This 这是我的例子。

    mapboxgl.accessToken = 'pk.eyJ1IjoibWFoYW5tZWhydmFyeiIsImEiOiJ6SDdSWldRIn0.8zUNm01094D1aoSeHpWYqA';
    var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v9',
        center: [51.40545845031738,
        35.75069181054449],
        zoom: 10
    
    });
    
    map.on('load', function (e) {
        // Add a layer showing the state polygons.
        map.addLayer({
            'id': 'states-layer',
            'type': 'fill',
            'source': {
                'type': 'geojson',
                'data': 'geojson.js'
            },
            'paint': {
                'fill-color': 'rgba(200, 100, 240, 0.4)',
                'fill-outline-color': 'rgba(200, 100, 240, 1)'
            }
        });
    
        // When a click event occurs on a feature in the states layer, open a popup at the
        // location of the click, with description HTML from its properties.
        map.on('click', 'states-layer', function (e) {
            new mapboxgl.Popup()
                .setLngLat(e.lngLat)
                //.setHTML(e.features[0].properties.name)
                .setHTML("<h1>"+e.features[0].properties.userone+"</h1>"+e.features[0].properties.name)
    
                .addTo(map);
        });
    
        // Change the cursor to a pointer when the mouse is over the states layer.
        map.on('mouseenter', 'states-layer', function () {
            map.getCanvas().style.cursor = 'pointer';
        });
    
        // Change it back to a pointer when it leaves.
        map.on('mouseleave', 'states-layer', function () {
            map.getCanvas().style.cursor = '';
        });
    });
    

    'paint': {
        'fill-color': 'rgba(200, 100, 240, 0.4)',
        'fill-outline-color': 'rgba(200, 100, 240, 1)'
    }
    

    在我的geojson文件中,我有一个颜色键:

    "type": "Feature",
    "properties": {
        "userone":"پیروزی",
        "name":"North Dafkota",
        "featureclass":"Admin-1 scale rank",
        "color":"red"
    }
    

    1 回复  |  直到 7 年前
        1
  •  9
  •   Andi-lo    7 年前

    如果您只想使用在geojson功能属性中定义的颜色。然后您可以像这样使用layers identity属性:

     map.addLayer({
        'id': 'states-layer',
        'type': 'fill',
        'source': {
            'type': 'geojson',
            'data': 'geojson.js'
        },
        'paint': {
            'fill-color': {
                type: 'identity',
                property: 'color',
            },
            'fill-outline-color': 'rgba(200, 100, 240, 1)'
        }
    });

    https://www.mapbox.com/mapbox-gl-js/style-spec/#function-type

    以及: https://www.mapbox.com/mapbox-gl-js/style-spec/#types-color