Reputation: 47
Hello I am using Mapbox GL JS but I am struggling displaying the map. I am having two issues:
LngLatLike
argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]My show page have the following script:
<script>
const mapToken = '<%-process.env.MAPBOX_TOKEN%>';
const campgroundGeometry = '<%- JSON.stringify(campground.geometry) %>'
</script>
<script src="/javascripts/showPageMap.js"></script>
My showPageMap file have this:
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)
I can see I am successfully getting the coordinates from the location in the Sources in my console through the campgroundGeometry function but I dont know what I am missing in my showPageMap page.
Here is an example of what I get in Sources:
const campgroundGeometry = '{"type":"Point","coordinates":[-122.419906,37.779026]}'
My map shows as a grey square in the app.
I am new to all this, thank you for the help.
Upvotes: 3
Views: 2571
Reputation: 492
You must parse the campgroundGeometry before accessing the coordinates and passing it to setLngLat
.
const campgroundGeometry = '{"type":"Point","coordinates":[-122.419906,37.779026]}'
const geometry = JSON.parse(campgroundGeometry);
new mapboxgl.Marker().setLngLat(geometry.coordinates);
Upvotes: 3
Reputation: 126457
Here is your problem:
const campgroundGeometry = '{"type":"Point","coordinates":[-122.419906,37.779026]}'
You have a string. You need an object.
Try this:
new mapboxgl.Marker()
.setLngLat(JSON.parse(campgroundGeometry.coordinates))
Upvotes: 0