Pop up on react leaflet map library

生来就可爱ヽ(ⅴ<●) 提交于 2020-04-18 03:47:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!