如何在传单中动态更改geojson多边形的颜色

how to dynamically change the color of a geojson polygon in leaflet

我正在使用 leaflet 来展示城市地图,并使用 geojson 来覆盖城市中的街区。我在我的 css 文件中设置了社区样式。我想做的是确定街区的名称和某些街区的名称为不同的颜色,但我不确定该怎么做。有人可以帮忙吗?

我的 geojson 文件很长,但开头是:

    var neighborhoods = {
    "features": [
    { "type": "Feature", "properties": { "objectid": 1293, "fid_blockg": 201, "statefp10": "42", "countyfp10": "003", "tractce10": "980600", "blkgrpce10": "1", "geoid10": "420039806001", "namelsad10": "Block Group 1", "mtfcc10": "G5030", "funcstat10": "S", "aland10": 982752, "awater10": 473795, "intptlat10": "+40.4518148", "intptlon10": "-080.0280506", "shape_leng": 19600.683115899999, "fid_neighb": 64, "area": 10688264.0, "perimeter": 80995.806272269998, "neighbor_": 35, "neighbor_i": 2117, "hood": "Chateau", "hood_no": 22, "acres": 246.501, "sqmiles": 0.383, "dpwdiv": 1, "unique_id": 113, "sectors": 3, "shape_le_1": 19607.9761334, "shape_ar_1": 10688263.843, "page_number": 15, "plannerassign": "Stephanie Joy Everett", "created_user": "pgh.admin", "created_date": "2020\/08\/14 14:52:26.925+00", "last_edited_user": "pgh.admin", "last_edited_date": "2020\/08\/14 14:52:26.925+00", "temp": null, "Shape__Area": 10687956.966918901, "Shape__Length": 19600.573084522901 }, "geometry": { "type": "Polygon", "coordinates": [ ... ] } }, 
...
more neighborhoods 
...

    ]
    }

css

path.leaflet-interactive {
    stroke-width: 1;
    stroke: #848484;
    fill: #DCDCDC; /*#e3c999;*/
    fill-opacity: .7;
    cursor: default;
}

jquery

var mymap = L.map('mapid').setView([40.4417, -80.0000], 12);
  L.tileLayer('https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png', {
    maxZoom: 20,
    attribution: '&copy; <a href="https://stadiamaps.com/">Stadia Maps</a>, &copy; <a href="https://openmaptiles.org/">OpenMapTiles</a> &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'

}).addTo(mymap);

    L.geoJson(neighborhoods).addTo(mymap); //neighborhoods variable was set in the geojson
    
    $.each(neighborhoods , function(index, item) { 
        for (var i = 0; i< 90; i++) {
            var str = item[i].properties.hood;
            
            if (str == "Strip District") {
                $(this).css('fill','#ffffff'); //doesn't work
                
            }
        }
        

这对我有用:

var layer = L.geoJSON(neighborhoods, {
     onEachFeature: function (feature, layer) {
        layer.bindTooltip(feature.properties.hood);
        if (feature.properties.hood == "Strip District") {
            layer.setStyle({fillColor :'#f7941d'}); 
        } else {
            layer.setStyle({fillColor :'#DCDCDC'}); 
        }
    }
    }).addTo(mymap);

如果你想在应用图层后改变颜色,你可以试试这个。您可以按功能将 geojson 拆分为一个数组,然后将这些功能添加到 layerGroup。然后,您可以使用 layerGroup.eachLayer() 功能访问所需的图层并使用 setStyle 设置所需的 color/fill。这是一个如何通过单击按钮更改图层颜色的示例:

import './style.css';
import mdGeojson from './maryland.json';

var mymap = L.map('mapid').setView([39.0458, -76.6413], 7);
var OpenStreetMap_Mapnik = L.tileLayer(
  'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
  {
    maxZoom: 19,
    attribution:
      '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
    layers: [OpenStreetMap_Mapnik, layerGroup],
  }
);
OpenStreetMap_Mapnik.addTo(mymap);

// Create a Leaflet layer group for the geojson layer:
var layerGroup = L.layerGroup().addTo(mymap);

// Spread each geojson feature into an array:
var regions = [...mdGeojson.features];
// console.log(regions)

// Iterate the array and place each layer individually:
regions.forEach((region) => {
  L.geoJson(region).addTo(layerGroup);
});

document.getElementById('button').addEventListener('click', () => {
  layerGroup.eachLayer((layer) => {
    // *** properties.name here will probably be properties.hood for you. 
    // This is simply retrieving the properties from the geojson:
    var name = Object.values(layer._layers)[0].feature.properties.name;
    // console.log(Object.values(layer._layers)[0].feature.properties.name);
    if (name === 'Baltimore City') {
      layer.setStyle(() => ({ color: 'orange', fillColor: 'orange' }));
    }
    if (name === 'Baltimore County') {
      layer.setStyle(() => ({ color: 'white', fillColor: 'white' }));
    }
    if (name === 'Montgomery County') {
      layer.setStyle(() => ({ color: 'red', fillColor: 'red' }));
    }
    if (name === 'Lower Shore') {
      layer.setStyle(() => ({ color: 'yellow', fillColor: 'yellow' }));
    }
  });
});
//

这是此处使用的 geojson 的 link、现场演示和一些重要的 Leaflet link: