首页 文章

Leaflet ReactJS Map不会完全显示tile

提问于
浏览
1

嗨,我正在尝试创建一个模态内的 Map . 但 Map 只是部分显示 . 我在创建节点后尝试使用invalidzeSIze()但它似乎不起作用 . 谢谢!

import React from 'react';
    import ReactDOM from 'react-dom'
    import L from 'leaflet';

    class Mapa extends React.Component {
        constructor(props){
            super(props);
            this.state = {
            };
        }

        createMap(element){
            var map = L.map(element);
            L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors'
            }).addTo(map);
            return map;
        }

        setupMap(){
            this.map.setView([this.props.lat, this.props.lon], this.props.zoom);
            this.map.invalidateSize();
        }

        componentDidMount(){
            let self = this;
            if (this.props.createMap) {
                this.map = this.props.createMap(ReactDOM.findDOMNode(self));
            } else {
                this.map = this.createMap(ReactDOM.findDOMNode(self));
            }

            this.setupMap();
        }

        render(){
            /*Returns div with id map*/
        }
    }

2 回答

  • 0

    我使用 JSS 做了这个:

    import jss from 'jss';
    import jssDefault from 'jss-preset-default';
    
    import 'leaflet/dist/leaflet.css';
    
    jss.setup(jssDefault());
    
    jss.createStyleSheet({
      '@global': {
        '.leaflet-container': {
          height: '100%',
        },
      },
    }).attach();
    

    Leaflet使用全局CSS类 . 所以你可以使用 css-loader 来使用你的全局样式:

    styles.css

    :global {
      .leaflet-container {
        height: 100%;
      }
    }
    

    component.jsx

    import './styles.css';
    
  • 0

    最后我修好了 . 代码是正确的但我没有正确添加传单依赖项 . 一旦我修复了所有工作完美 . 实际上this.map.invalidateSize();没有必要 .

    import React from 'react';
        import ReactDOM from 'react-dom'
        import L from 'leaflet';
    
        class Mapa extends React.Component {
            constructor(props){
                super(props);
                this.state = {
                };
            }
    
            createMap(element){
                var map = L.map(element);
                L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                    attribution: '© OpenStreetMap contributors'
                }).addTo(map);
                return map;
            }
    
            setupMap(){
                this.map.setView([this.props.lat, this.props.lon], this.props.zoom);
            }
    
            componentDidMount(){
                let self = this;
                if (this.props.createMap) {
                    this.map = this.props.createMap(ReactDOM.findDOMNode(self));
                } else {
                    this.map = this.createMap(ReactDOM.findDOMNode(self));
                }
    
                this.setupMap();
            }
    
            render(){
                /*Returns div with id map*/
            }
        }
    

相关问题