I have a issue with converting longitute and latitute into a array my code is like this:

<div> <div id='map' style='width: 100%; height: 100%; margin: 0px;'></div> <script> mapboxgl.accessToken = 'pk.eyJ1IjoibGl2ZS1vbGRoYW0iLCJhIjoiY2ozbXk5ZDJ4MDAwYjMybzFsdnZwNXlmbyJ9.VGDuuC92nvPbJo-qvhryQg'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v10', center: [-1.77, 52.73], zoom: 3 }); map.addControl(new MapboxGeocoder({ accessToken: mapboxgl.accessToken })); map.on('click', function(e) { var test = JSON.stringify(e.lngLat); test.toArray(); console.log(test); mapboxgl.Marker() .setLngLat(test) .addTo(map); }); 

test is returning value as:

{"lng":-2.8246875000017155,"lat":52.72999999999914}

However, the value needs to be as:

[-2.8246875000017155, 52.72999999999914]

So toArray should work but I get

Uncaught TypeError: test.toArray is not a function
at e. (1:181)
at e.Evented.fire (evented.js:87)
at h (bind_handlers.js:139)
at HTMLDivElement.s (bind_handlers.js:114)

Edit

map.on('click', function(e) { var test = e.lngLat; console.log(test); test.toArray(); mapboxgl.Marker() .setLngLat(test) .addTo(map); }); 

But now I get:

Uncaught TypeError: Cannot read property 'bind' of undefined

11

2 Answers

The issue is you have to create a new marker. If you follow the code in the documentation it should work.

Try the following modification to your code

map.on('click', function (e) { new mapboxgl.Marker() .setLngLat(e.lngLat) .addTo(map); }); 

Edit

Nothing will appear as a marker, you have to style that yourself as far as I'm aware, try adding this CSS to see something.

.mapboxgl-marker { width: 10px; height: 10px; background-color: purple; } 
0

You could try the following:

var longLatArray = []; longLatArray.push(e.lng); longLatArray.push(e.lat); mapboxgl.Marker() .setLngLat(longLatArray) .addTo(map); 
5

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy