gpt4 book ai didi

javascript - React leaflet map 库中的GeoJSON样式

转载 作者:行者123 更新时间:2023-12-02 21:22:32 24 4
gpt4 key购买 nike

我已经在我的react项目中实现了传单 map 库https://react-leaflet.js.org/en/并实现了如下所示的 geojson map 组件

class MapContainer extends React.Component {
state = {
greenIcon: {
lat: 8.3114,
lng: 80.4037
},
zoom: 8
};

grenIcon = L.icon({
iconUrl: leafGreen,
iconSize: [24, 24], // size of the icon
//iconAnchor: [22, 94], // point of the icon which will correspond to marker's location
popupAnchor: [-3, -16]
});

render() {

const positionGreenIcon = [
this.state.greenIcon.lat,
this.state.greenIcon.lng
];

return (
<div className="mapdata-container">
<Map className="map" style={{height:'100%',width:'100%'}} center={positionGreenIcon} zoom={this.state.zoom}>
<GeoJSON data={geo}/>
<Marker position={positionGreenIcon} icon={this.grenIcon}>
<Popup>I am a green leaf</Popup>
</Marker>
</Map>
</div>
);
}
}

export default MapContainer;

看起来像这样

enter image description here

我想用不同的颜色为每个省份着色,但文档中没有太多关于如何执行此操作的信息。

这是我使用的 geojson 文件。 https://raw.githubusercontent.com/thejeshgn/srilanka/master/electoral_districts_map/LKA_electrol_districts.geojson

如何用不同的颜色填充每个省份。

最佳答案

您可以在 GeoJSON 包装器上使用 style 属性轻松实现这一点。创建一个接受该功能作为参数的样式方法。然后在 fillColor 属性中使用属性:{ electoralDistrict } 来标识选区并返回所需的颜色:以下是一个示例:

class MapContainer extends React.Component {
state = {
greenIcon: {
lat: 8.3114,
lng: 80.4037
},
zoom: 8
};

grenIcon = L.icon({
iconSize: [24, 24], // size of the icon
//iconAnchor: [22, 94], // point of the icon which will correspond to marker's location
popupAnchor: [-3, -16],
iconUrl: leafGreen
});

giveColor = district => {
switch (district) {
case "Matara":
return "red";
case "Polonnaruwa":
return "brown";
case "Ampara":
return "purple";
default:
return "white";
}
};

style = feature => {
const {
properties: { electoralDistrict }
} = feature;
return {
fillColor: this.giveColor(electoralDistrict),
weight: 0.3,
opacity: 1,
color: "purple",
dashArray: "3",
fillOpacity: 0.5
};
};

render() {
const positionGreenIcon = [
this.state.greenIcon.lat,
this.state.greenIcon.lng
];

return (
<div className='mapdata-container'>
<Map
className='map'
style={{ height: "100vh", width: "100%" }}
center={positionGreenIcon}
zoom={this.state.zoom}
>
<GeoJSON data={geo} style={this.style} />
<Marker position={positionGreenIcon} icon={this.grenIcon}>
<Popup>I am a green leaf</Popup>
</Marker>
</Map>
</div>
);
}
}

关于javascript - React leaflet map 库中的GeoJSON样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60810713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com