我已经在我的react项目https://react-leaflet.js.org/en/中实现了传单地图库,并实现了如下的geojson地图组件
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;
看起来像这样
我想用不同的颜色给每个省上色,并且文档中对此没有很多说明。
这是我使用过的geojson文件。https://raw.githubusercontent.com/thejeshgn/srilanka/master/electoral_districts_map/LKA_electrol_districts.geojson
我如何fill
每个省使用不同的颜色。
您可以在GeoJSON包装器上使用style
属性轻松实现。创建一个接受该特征作为参数的样式方法。然后在fillColor属性中使用以下属性:{eleuralDistrict}来标识区域并返回所需的颜色:这是一个可能的示例:
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>
);
}
}