最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add a legend to the map using react leaflet, without using refs and manually modifying the DOM? - Stack Over

programmeradmin2浏览0评论

I'm using react-leaflet and want to add a legend to the map.

I can currently do it by passing a ref of the map to a custom ponent and render null while having a function create the HTML and add it to the map. The refs are being a nightmare to test using Jest and Enzyme.

Is there a way to using a react-leaflet ponent to acplish this?

I'm using react-leaflet and want to add a legend to the map.

I can currently do it by passing a ref of the map to a custom ponent and render null while having a function create the HTML and add it to the map. The refs are being a nightmare to test using Jest and Enzyme.

Is there a way to using a react-leaflet ponent to acplish this?

Share Improve this question asked Aug 7, 2019 at 23:36 bhagwansbhagwans 1631 silver badge10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

You can achieve that by extending react-leaflet's MapControl class and using for instance the legend code provided by Leaflet official page tutorial for Using GeoJSON with Leaflet.

class Legend extends MapControl {
   ponentDidMount() {
      // place your code here

      ...
      const legend = L.control({ position: "bottomright" });

      ...
      const { map } = this.props.leaflet;
      legend.addTo(map);
   }
}

and then import it here:

 <Map style={{ height: "100vh" }} center={position} zoom={13}>
        <TileLayer
          url="https://{s}.tile.openstreetmap/{z}/{x}/{y}.png"
          attribution='&copy; <a href="http://osm/copyright">OpenStreetMap</a> contributors'
        />
        <Legend />
 </Map>

Demo

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论