你好,我正在使用 Mapbox GL JS,但我很难显示地图。我有两个问题:
LngLatLike
argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or array of [, ]我的展示页面有以下脚本:
<script>
const mapToken = '<%-process.env.MAPBOX_TOKEN%>';
const campgroundGeometry = '<%- JSON.stringify(campground.geometry) %>'
</script>
<script src="/javascripts/showPageMap.js"></script>
我的 showPageMap 文件有这个:
mapboxgl.accessToken = mapToken;
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10', // stylesheet location
center: campgroundGeometry.coordinates, // starting position [lng, lat]
zoom: 8//
})
new mapboxgl.Marker()
.setLngLat(campgroundGeometry.coordinates)
.setPopup(
new mapboxgl.Popup({ offset: 25 })
.setHTML(
`<h3>${campground.title}</h3><p>${campground.location}</p>`
)
)
.addTo(map)
我可以看到我通过 campgroundGeometry 函数成功地从控制台中的源位置获取坐标,但我不知道我的 showPageMap 页面中缺少什么。
这是我在资源中得到的一个例子:
const campgroundGeometry = '{"type":"Point","coordinates":[-122.419906,37.779026]}'
我的地图在应用程序中显示为灰色方块。
我对这一切都是陌生的,谢谢你的帮助。
这是你的问题:
const campgroundGeometry = '{"type":"Point","coordinates":[-122.419906,37.779026]}'
你有一个字符串。你需要一个对象。
试试这个:
new mapboxgl.Marker()
.setLngLat(JSON.parse(campgroundGeometry.coordinates))