bry*_*ant 2 javascript leaflet mapbox reactjs
我正在学习使用react和mapbox,但我正在努力解决为什么我的mapbox地图在通过React加载时无法正确呈现.当我正常加载它(没有React.js)时,没有问题,因为下面的代码工作并且地图正常显示:
<script src="https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.css"/>
<div> id="map"></div>
<script>
var map = L.mapbox.map('map', 'blabla.blabla').setView([lat, long], 9);
</script>
Run Code Online (Sandbox Code Playgroud)
但是当我按照以下方式进行操作时,地图通常根本不显示,或者当它出现时,我只看到div左上角的一部分.
<script src="path/to/react.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.css"/>
<div id="react-content">
<script src="path/to/react/content.js'></script>
</div>
//now inside react/content.js, there is a mapbox component inside an outer component. I'm leaving out the rest of the code to save space, and I believe that I am rendering the OuterComponent and the MapBoxMap component correctly inside that.
var MapBoxMap = React.createClass({
componentDidMount: function() {
L.mapbox.accessToken = this.props.accessToken;
var map = L.mapbox.map(this.getDOMNode(), this.props.mapId)
.setView([15, -105], 9);
},
render: function() {
return (
<div id="map"></div>
);
}
});
Run Code Online (Sandbox Code Playgroud)
像缩放或打开chrome开发工具这样的事情似乎有时会使地图出现.我不知道发生了什么事.尝试渲染地图时,组件是否未正确安装?我以为这是componentDidMount应该照顾的?我真的很感激任何见解!Alos,这张地图正在一些Zurb Foundation元素中呈现,所以我不知道这是否有所作为?
你错过了相关的CSS?您始终需要设置元素的高度:
html, body, #map {
height: 100%;
}
Run Code Online (Sandbox Code Playgroud)
由于React,我无法测试,但听起来地图无法从元素中获取正确的尺寸.如果你没有设置正确的CSS或元素有,通常会发生这种情况.display: none;如果设置正确的CSS不起作用,你可以尝试使大小无效,以便地图重置自己.L.mapbox.Map有一个invalidateSize你可以打电话的方法,见:
http://leafletjs.com/reference.html#map-invalidatesize