Good way to combine React and Leaflet

后端 未结 2 1487
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 04:20

I am working on a project to combine React and Leaflet, but I must say I am having some hard time with the semantics.

As most of the stuff is managed by Leaflet directly

相关标签:
2条回答
  • 2021-01-30 04:50

    As an additional, less-detailed answer, PaulLeCam's react-leaflet component seems popular. Haven't used it yet but it looks promising:

    https://github.com/PaulLeCam/react-leaflet

    UPDATE: It's solid. Haven't used many of the features yet but the codebase is well-written and easy to follow and extend, and what I've used works great out of the box.

    0 讨论(0)
  • 2021-01-30 04:55
    • You don't need to manage uniqueness, i.e. "UID", yourself. Instead, you can use getDOMNode to access the component's real node. Leaflet's API supports either a string selector or an HTMLElement instance.
    • Leaflet is managing rendering, so the map should not live on state. Only store data in state that affects React's rendering of the DOM element.

    Beyond those two points, use the Leaflet API normally and tie callbacks from your React component to the Leaflet map as you like. React is simply a wrapper at this point.

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    class Livemap extends React.Component {
    
        componentDidMount() {
            var map = this.map = L.map(ReactDOM.findDOMNode(this), {
                minZoom: 2,
                maxZoom: 20,
                layers: [
                    L.tileLayer(
                        'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                        {attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'})
                ],
                attributionControl: false,
            });
    
            map.on('click', this.onMapClick);
            map.fitWorld();
        }
    
        componentWillUnmount() {
            this.map.off('click', this.onMapClick);
            this.map = null;
        }
    
        onMapClick = () => {
            // Do some wonderful map things...
        }
    
        render() {
            return (
                <div className='map'></div>
            );
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题