reactjs - 如何在 React 中实现一个基本的 mapbox gl
问题描述
嗨,我在 mapbox 中使用了代码示例,但它什么也没显示(宽度 = 0)请指导我,如何在 react js 中实现地图。这是我的 index.js 文件:
mapboxgl.accessToken =
"My 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)
});
});
}
解决方案
您必须为 mapbox contianer 指定宽度和高度。以下是如何让它工作:
import React from "react";
import "./styles.css";
import mapboxgl from "mapbox-gl";
mapboxgl.accessToken =
"<token>";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
lng: 5,
lat: 34,
zoom: 2
};
}
componentDidMount() {
const map = new mapboxgl.Map({
container: "map",
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
id="map"
style={{
width: "100vw",
height: "100vh"
}}
/>
);
}
}
推荐阅读
- python - 从零变为非零的数据框中选择日期时间?
- ios - 如何永远生成图像?精灵套件
- javascript - Vuejs 使用路由 href 链接传递参数
- python - 初学者 - 查找点所在的“区域”
- javascript - 单击按钮时的 if 语句
- reactjs - 添加活动类以使用子链接反应组件
- reactjs - 如何使用历史记录中的 createHashHistory 从 url 中删除 #
- regex - 正则表达式检查分隔字符串中的数字长度
- ios - 如何使用 CoreBluetooth 和 Swift 将蓝牙连接保存到设置
- css - 如何从 monaco-editor 的上下文菜单中删除选项?