问题
I'm using react-leaftlet
map library https://react-leaflet.js.org/en/ in my react app and i have rendered some markers on the map and when a user clicks on a marker, a pop up appears. I want to open a similar popup when a user clicks on the district of my map as well. How can i do that? The following is my code to render the markers with popup. (The map is rendered using geojson data)
markerHospitalRender() {
return this.props.hospitalData.map(item => {
const position = [item.district_lat, item.district_long];
return (
<Marker position={position} icon={this.grenIcon}>
<Popup>
<span style={{ display: "block" }}>{item.name}</span>
</Popup>
</Marker>
);
});
}
<Map
className="map"
center={center}
>
<GeoJSON
data={geo}
style={this.hospital_style}
/>
{this.markerHospitalRender()}
</Map>
回答1:
Use onEachFeature
prop on react-leaflet
's GeoJSON
wrapper to pass an arrow function similarly to native's leaflet onEachFeature
function to be able to generate a popup when clicking on each district.
<GeoJSON
data={geo}
style={this.hospital_style}
onEachFeature={onEachFeature}
/>
const onEachFeature = (feature, layer) => {
const popupContent = `District Code: ${feature.properties.electoralDistrictCode} <br> District: ${feature.properties.electoralDistrict}`;
if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent);
};
来源:https://stackoverflow.com/questions/60878939/pop-up-on-react-leaflet-map-library