首页 > 解决方案 > 带有反应和 mapbox gl 的 Mapbox GL 应用程序不起作用

问题描述

我按照使用 react 和 Mapbox GL 的 Mapbox 教程进行操作,并且没有与代码相关的问题,但是当我在浏览器(chrome)上启动应用程序时,它会显示一个带有坐标的空白页面。似乎应用程序本身可以工作,但它没有显示地图。

这是我的代码:

html

<!DOCTYPE html>
<html lang='en'>
<head>
<title>Mapbox GL JS and React</title>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.3.1/mapbox-gl.css' rel='stylesheet' />
<link href='site.css' rel='stylesheet'/>
</head>
<body>
<div id='app'></div>
</body>
</html>

CSS:

.sidebarStyle {
display: inline-block;
position: absolute;
top: 0;
left: 0;
margin: 12px;
background-color: #404040;
color: #ffffff;
z-index: 1 !important;
padding: 6px;
font-weight: bold;
}
 
.mapContainer {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
}

js:

import React from 'react';
import ReactDOM from 'react-dom';
import mapboxgl from 'mapbox-gl';
 
mapboxgl.accessToken = 'MAPBOX_ACCESS_TOKEN';
 
class Application extends React.Component {
constructor(props) {
super(props);
this.state = {
lng: 5,
lat: 34,
zoom: 2
};
}
 
componentDidMount() {
const map = new mapboxgl.Map({
container: this.mapContainer,
style: 'mapbox://styles/mapbox/streets-v11',
center: [this.state.lng, this.state.lat],
zoom: this.state.zoom
});
 
map.on('move', () => {
this.setState({
lng: map.getCenter().lng.toFixed(4),
lat: map.getCenter().lat.toFixed(4),
zoom: map.getZoom().toFixed(2)
});
});
}
 
render() {
return (
<div>
<div className='sidebarStyle'>
<div>Longitude: {this.state.lng} | Latitude: {this.state.lat} | Zoom: {this.state.zoom}</div>
</div>
<div ref={el => this.mapContainer = el} className='mapContainer' />
</div>
)
}
}
 
ReactDOM.render(<Application />, document.getElementById('app'));

标签: reactjsvisual-studio-codemapbox-gl-js

解决方案


推荐阅读