问题描述
我目前正在开发一个包含地图的react应用,该地图上需要标记。目前,我已经有了地图,并且已经按照自己想要的方式对其进行了样式设置,但是当我绘制一个标记时,该标记已经偏离了它应该位于的实际点。我正在使用mapBox-gl作为似乎缺少的react-mapBox-gl的文档。
应将其绘制在科罗拉多州的丹佛市,但在某些情况下应将其完全缩小到地图组件之外。
console.log("Map props",props)
const [map,setMap] = useState(null)
const mapContainerRef = useRef(null)
let mapBoxgl = require('mapBox-gl/dist/mapBox-gl.js');
useEffect(() => {
const map = new mapBoxgl.Map({
container: mapContainerRef.current,style: 'mapBox://styles/mapBox/streets-v11',center: [-104.9876,39.7405],zoom: 7,});
let marker = new mapBoxgl.Marker({color: 'blue'})
.setLngLat([-104.9876,39.7405])
.addTo(map)
},[]);
return (
<div ref={el => (mapContainerRef.current = el)} style={{height: '50em',width: '100%'}} />
)
}```
Before anyone says anything I have the token within my code currently so that is not the issue.
解决方法
我已解决此问题,方法是改为使用react-mapbox-gl,然后使用以下代码在地图上放置一个小圆圈。
<Map
style="mapbox://styles/mapbox/streets-v9"
containerStyle={{
height: "calc(100vh - 130px)",width: "100%"
}}
center={[-0.5225869881734102,53.235052086599545]}
zoom={[16]}
>
{/* Map Marker */}
<Layer
type="symbol"
layout={{ "icon-image": "circle-15","icon-size": 1.5 }}>
<Feature
coordinates={[-0.5371284484863282,53.23427159260936]}
/>
</Layer>
</Map>
我继续弄乱react-mapbox-gl上下文api,并使用以下代码设法复制了确切的mapbox标记示例。
<MapContext.Consumer>
{(map) => {
let mapboxgl = require('mapbox-gl/dist/mapbox-gl.js');
var marker = new mapboxgl.Marker()
.setLngLat([12.550343,55.665957])
.addTo(map);
}}
</MapContext.Consumer>
彻底消除问题。