我正在尝试使用 React 来处理 MapBox。我已经使用 create-react-app 创建了项目,添加了 mapbox-gl ("mapbox-gl": "^0.46.0-beta.1"),但是我的 css 文件有问题。它向我显示了这个警告:
This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in
https://www.mapbox.com/mapbox-gl-js/api/
我已执行所有步骤:
1 - 安装 npm 包:npm install --save mapbox-gl
2 - 将 CSS 文件包含在 HTML 文件中:<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.45.0/mapbox-gl.css' rel='stylesheet' />
.
但是我如何在 ES6 中使用 React,我已经在 index.js css 文件中添加了 import 'mapbox-gl/dist/mapbox-gl.css';
如果我导入 css 文件,它不会向我显示任何内容,如果我评论导入,它会显示没有设计的 map ,并且会显示警告。
怎么解决呢???感谢您的帮助
这是我的代码:
import React, { Component } from 'react';
import mapboxgl from 'mapbox-gl';
mapboxgl.accessToken = 'my_token';
class MapComponent extends Component {
constructor(props) {
super(props);
this.state = {
lng: 1.2217,
lat: 39.8499,
zoom: 6.48
};
}
componentDidMount() {
const { lng, lat, zoom } = this.state;
var map = new mapboxgl.Map({
container: 'map',
center: [lng, lat],
style: 'mapbox://styles/mapbox/streets-v10',
zoom: zoom
});
map.on('move', () => {
const { lng, lat } = map.getCenter();
this.setState({
lng: lng.toFixed(4),
lat: lat.toFixed(4),
zoom: map.getZoom().toFixed(2)
});
});
}
render() {
const { lng, lat, zoom } = this.state;
return (
<div className="App">
<div className="inline-block absolute top left mt12 ml12 bg-darken75 color-white z1 py6 px12 round-full txt-s txt-bold">
<div>{`Longitude: ${lng} Latitude: ${lat} Zoom: ${zoom}`}</div>
</div>
<div id="map" />
</div>
);
}
}
export default MapComponent;
解决方案:
正如我所说,我添加了mapbox-gl.css,import 'mapbox-gl/dist/mapbox-gl.css';
但不显示 map 。
在 css 文件上显示下一个 css 属性:
<canvas class="mapboxgl-canvas" tabindex="0" aria-label="Map" width="951" height="844" style="position: absolute; width: 951px; height: 844px;"></canvas>
我通过以下方式修改了 Canvas 属性:
.mapboxgl-canvas {
position: fixed !important;
height: 100% !important;
}
最佳答案
1 - 导入“mapbox-gl/dist/mapbox-gl.css”;
2 - 覆盖名为 .mapboxgl-canvas 的 css 类
.mapboxgl-canvas {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
}
关于reactjs - 使用 React 缺少 MapBox CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50909438/