'How can I measure the distance between where I'm at the moment and the first circle I have drawn on the map?
I have an application where I can draw a route so a simulation start where a boat is following that route. What I want to know is how I could measure the distance between me and the first Circle that I draw in the route(so the start point of the boat)
the circle on the right is my current location and the circle on the left is the first dot that I have drawn.
this is how I get my current location
navigator.geolocation.getCurrentPosition(position => {
console.log(position.coords.latitude, position.coords.longitude);
});
and this is how I draw and get the coordinates of the route
// gives the function to be able to draw lines in the map to make a route
var draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
line_string: true
},
styles: [
// ACTIVE (being drawn)
// line stroke
{
"id": "gl-draw-line",
"type": "line",
"filter": ["all", ["==", "$type", "LineString"], ["!=", "mode", "static"]],
"layout": {
"line-cap": "round",
"line-join": "round"
},
"paint": {
"line-color": "#3b9ddd",
"line-dasharray": [0.2, 2],
"line-width": 4,
"line-opacity": 0.7
}
},
{
"id": "gl-draw-polygon-and-line-vertex-halo-active",
"type": "circle",
"filter": ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"], ["!=", "mode", "static"]],
"paint": {
"circle-radius": 10,
"circle-color": "#FFF"
}
},
// vertex points
{
"id": "gl-draw-polygon-and-line-vertex-active",
"type": "circle",
"filter": ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"], ["!=", "mode", "static"]],
"paint": {
"circle-radius": 6,
"circle-color": "#3b9ddd",
},
}
]
});
map.addControl(new mapboxgl.FullscreenControl());
map.addControl(geolocate)
map.addControl(new mapboxgl.NavigationControl());
map.addControl(draw);
// add create, update, or delete actions
map.on('draw.create', updateRoute);
map.on('draw.update', updateRoute);
map.on('draw.delete', removeRoute);
// use the coordinates you just drew to make your directions request
function updateRoute() {
removeRoute(); // overwrite any existing layers
var data = draw.getAll();
var lastFeature = data.features.length - 1;
coords = data.features[lastFeature].geometry.coordinates;
}
So basically I want to measure between the distance between position.coords.latitude, position.coords.longitude and coords[0]
Solution 1:[1]
You can calculate the distance between two coordinates using LngLat.distanceTo()
Something like:
const start = new Mapbox.LngLat(...coords);
const end = new Mapbox.LngLat(position.coords.longitude, position.coords.latitude);
const dist = start.distanceTo(end);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Steve Bennett |

