I’ve been working on a mapping project and encountered a problem where I need to find a point exactly between two given points on a map, at a specific distance from one of the points. I’ve tried various approaches, but haven’t been able to achieve the desired result.
I’ve researched and found a formula to calculate the distance between two points on the Earth’s surface, and I’ve adjusted it accordingly. Now, I’m trying to use this formula to find a third point on the map that lies exactly between the two given points and is at a specific distance from one of them.
Here’s what I’ve tried so far:
// Variable declare
let start_get_lat = 31.5387761;
let start_get_lng = 72.9696664;
let end_get_lat = 31.569235;
let end_get_lng = 72.983557;
let center = {lat: Number(start_get_lat), lng: Number(start_get_lng)};
let endLocation = {lat: Number(end_get_lat), lng: Number(end_get_lng)};
Calculate distance bw two points and
// calculate distance function
const distance = calculateDistance(lat1, lon1, centerLat, centerLon);
Get point bwtween function and usage
function getPointBetween(startLat, startLng, endLat, endLng, distance) {
const earthRadius = 6371000; // Earth's radius in meters
// Convert latitudes and longitudes from degrees to radians
const lat1 = startLat * Math.PI / 180;
const lon1 = startLng * Math.PI / 180;
const lat2 = endLat * Math.PI / 180;
const lon2 = endLng * Math.PI / 180;
// Calculate the angular distance between the points
const delta = distance / earthRadius;
// Calculate the intermediate point
const A = Math.sin((1 - delta) * Math.PI / 2) + Math.sin(delta * Math.PI / 2) * Math.cos(lat1) * Math.cos(lat2);
const B = Math.sin(delta * Math.PI / 2) * Math.sin(lon2 - lon1) * Math.cos(lat2);
const C = Math.atan2(B, A);
const lat3 = Math.asin(A * Math.sin(lat1) + B * Math.sin(lat2)) * 180 / Math.PI;
const lon3 = (lon1 + Math.atan2(Math.sin(lon2 - lon1) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) + Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1))) * 180 / Math.PI;
return { lat: lat3, lng: lon3 };
}
let anyDistance = distance - 1000;
const pointBetween = getPointBetween(start_get_lat, start_get_lng, end_get_lat, end_get_lng, anyDistance);
let bwMarker = new google.maps.Marker({
position: pointBetween,
map: map,
title: "Center",
fillColor: 'blue', //
});
console.log(pointBetween);
However, while this function returns a point between the two coordinates, it does not guarantee that the point lies exactly on the line segment between them at the specified distance. The goal is to achieve a precise displacement from one of the given points.
I’m looking for insights or alternative manual calculation methods to achieve this precise displacement between two coordinates without using google map, as I need a solution that can be implemented in both front-end and back-end environments.
Any suggestions or advice would be greatly appreciated. Thank you for your time and assistance!