Nit*_*ndo 5 reactjs mapbox-gl-js
我是第一次使用mapboxgl。我从github上找到了源代码。地图工作正常,但标记显示在地图之外。不明白有什么问题..
代码如下_
import React, { Component } from "react";
import ReactDom from "react-dom";
import mapboxgl from "mapbox-gl";
mapboxgl.accessToken =
"pk.eyJ1Ijoibml0dGFuYW5kbyIsImEiOiJja3AzeGsxdXUxd2dtMnBvMjFncHV2MWQzIn0.T3wHeHz_mCHk1AcExPm8mA";
const data = [
{
location: "Panthapath",
city: "Dhaka",
state: "Bangladesh",
coordinates: [90.38382231219224, 23.75296142856617],
},
];
class Gmap extends React.Component {
constructor(props) {
super(props);
this.state = {
lng: 90.38382231219224,
lat: 23.75296142856617,
zoom: 16,
};
}
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,
});
data.forEach((location) => {
console.log(location);
var marker = new mapboxgl.Marker()
.setLngLat(location.coordinates)
.setPopup(
new mapboxgl.Popup({ offset: 30 }).setHTML(
"<h4>" + location.city + "</h4>" + location.location
)
)
.addTo(map);
});
}
render() {
return (
<div>
<div
ref={(el) => (this.mapContainer = el)}
style={{ width: "80%", height: "80vh", margin: "0 auto" }}
/>
</div>
);
}
}
export default Gmap;
Run Code Online (Sandbox Code Playgroud)
在终端中显示错误“标记已定义但从未使用”。但地图正在按预期加载,标记位于地图部分之外
您可以在App.js中导入mapbox-gl.css文件。这对于 nextjs 也有效。在 next.js 中,如果您的地图组件在其中,则可以将其添加到pages/next.js 中。
import 'mapbox-gl/dist/mapbox-gl.css';
Run Code Online (Sandbox Code Playgroud)
我找到了解决方案。在index.html文件标记中添加mapbox-gl.css后就可以了。
<link href="https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css" rel="stylesheet">
Run Code Online (Sandbox Code Playgroud)
我的程序是反应。
| 归档时间: |
|
| 查看次数: |
1638 次 |
| 最近记录: |