1

我正在尝试在 React 项目中使用 Leaflet。我的目标实际上是非常基本的:只显示一个 openstreetMap 图层(没有标记或东西)

这是我的代码:

import React, { Component } from 'react';
import L from 'leaflet';

class MyMap extends Component {

  constructor(){
    super();
    this.state ={
      map:null,
    };
  }

componentDidMount() {
        var map = L.map('map', {
            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,
        });
        return this.setState({
            map: map
        });
    }
    render() {
        return (
            <div id='map'> </div>
        );
    }

}

ReactDOM.render(
  <MyMap />,
  document.getElementById('root')
);

每次我有显示地图的保存问题时:它看起来像这样:(并非所有图块都显示,它们是叠加问题): 截图

有人面临这个问题或有任何解决方案吗?

感谢您的帮助

4

1 回答 1

2

首先,确保您已加载 Leaflet 的样式表:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">

由于样式表尚未加载或 Leaflet 在 React 实际呈现地图目标后执行,所以会发生瓷砖的洗牌。我们可以做的是为初始化添加一个超时:

class MyMap extends React.Component {
  constructor() {
    super();
    this.state ={
      map: null,
    };
  }

  componentDidMount() {
    setTimeout(() => {
      var map = L.map('map', {
          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.fitWorld();
      return this.setState({
          map: map
      });
    }, 100)
  }

  render() {
    return <div id="map" style={{ height: 300 }}></div>;
  }
}

ReactDOM.render(
  <MyMap />,
  document.getElementById('View')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">
<div id="View"></div>

于 2016-11-13T22:31:27.937 回答