我正在尝试在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: '© <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
有人面对这个问题还是有任何解决方案?
感谢您的帮助
答案 0 :(得分:1)
首先,请确保您已在Leaflet的样式表中加载:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">
瓦片的随机发生是因为样式表尚未加载或者在React实际渲染地图目标后执行Leaflet。我们可以做的是为初始化添加超时:
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: '© <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')
);
&#13;
<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>
&#13;