2016-11-13 94 views
1

我正在尝试在React项目上使用Leaflet。 我的目标其实很简单:只是显示的OpenStreetMap层(无标记或东西)React和Leaflet - 显示图层的问题

这里是我的代码:

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') 
); 

每次我有救的问题,以显示地图: 它看起来像这样:(不是所有的瓷砖显示,他们是重叠问题): Screenshot

是有人面对这个问题或有任何解决方案?

谢谢您的帮助

回答

1

首先,确保你已经在宣传单的样式表加载:

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

瓷砖的洗牌发生,因为无论是样式表尚未加载或执行传单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>

+0

我有同样的问题。正如你已经提到的,我忘记了包含Leaflet的样式表。 React Leaflet模块不包括Leaflet的样式表和[这是原因](https://github.com/PaulLeCam/react-leaflet/issues/75#issuecomment-232908434)。 –

+0

它很有意义,虽然很容易忘记。感谢您的链接! –

+0

谢谢!事实上,我忘了加载传单样式表。并与setTimeOut(),它完美的作品 –