Related
I'm trying to use the Haversine Distance Formula (as found here: http://www.movable-type.co.uk/scripts/latlong.html) but I can't get it to work, please see the following code
function test() {
var lat2 = 42.741;
var lon2 = -71.3161;
var lat1 = 42.806911;
var lon1 = -71.290611;
var R = 6371; // km
//has a problem with the .toRad() method below.
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
alert(d);
}
And the error is:
Uncaught TypeError: Object -0.06591099999999983 has no method 'toRad'
Which I understand to be because it needs to do the following:
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
But when I put this below the function, it still comes back with the same error message. How do I make it use the helper method? Or is there an alternative way to code this to get it to work? Thanks!
This code is working:
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
var lat2 = 42.741;
var lon2 = -71.3161;
var lat1 = 42.806911;
var lon1 = -71.290611;
var R = 6371; // km
//has a problem with the .toRad() method below.
var x1 = lat2-lat1;
var dLat = x1.toRad();
var x2 = lon2-lon1;
var dLon = x2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
alert(d);
Notice how I defined x1 and x2.
Play with it at: https://tinker.io/3f794
Here's a refactored function based on 3 of the other answers!
Please note that the coords arguments are [longitude, latitude].
function haversineDistance(coords1, coords2, isMiles) {
function toRad(x) {
return x * Math.PI / 180;
}
var lon1 = coords1[0];
var lat1 = coords1[1];
var lon2 = coords2[0];
var lat2 = coords2[1];
var R = 6371; // km
var x1 = lat2 - lat1;
var dLat = toRad(x1);
var x2 = lon2 - lon1;
var dLon = toRad(x2)
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
if(isMiles) d /= 1.60934;
return d;
}
ES6 JavaScript/NodeJS refactored version:
/**
* Calculates the haversine distance between point A, and B.
* #param {number[]} latlngA [lat, lng] point A
* #param {number[]} latlngB [lat, lng] point B
* #param {boolean} isMiles If we are using miles, else km.
*/
const haversineDistance = ([lat1, lon1], [lat2, lon2], isMiles = false) => {
const toRadian = angle => (Math.PI / 180) * angle;
const distance = (a, b) => (Math.PI / 180) * (a - b);
const RADIUS_OF_EARTH_IN_KM = 6371;
const dLat = distance(lat2, lat1);
const dLon = distance(lon2, lon1);
lat1 = toRadian(lat1);
lat2 = toRadian(lat2);
// Haversine Formula
const a =
Math.pow(Math.sin(dLat / 2), 2) +
Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);
const c = 2 * Math.asin(Math.sqrt(a));
let finalDistance = RADIUS_OF_EARTH_IN_KM * c;
if (isMiles) {
finalDistance /= 1.60934;
}
return finalDistance;
};
See codepen for tests against accepted answer: https://codepen.io/harrymt/pen/dyYvLpJ?editors=1011
Why not try the straight forward solution? Instead of extending Number prototype, just define toRad as a regular function:
function toRad(x) {
return x * Math.PI / 180;
}
and then call toRad everywhere:
var dLat = toRad(lat2-lat1);
Extending the Number prototype does not always work as expected. For example calling 123.toRad() does not work. I think that if you do var x1 = lat2 - lat1; x1.toRad(); works better than doing (lat2-lat1).toRad()
when I put this below the function
You only need to put it above the point where you call test(). Where the test function itself is declared does not matter.
You need to extend the Number prototype, before calling those extensions in a function.
So just ensure
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
is called before your function is called.
Another variant to reduce redundancy and also compatible with Google LatLng objects:
function haversine_distance(coords1, coords2) {
function toRad(x) {
return x * Math.PI / 180;
}
var dLat = toRad(coords2.latitude - coords1.latitude);
var dLon = toRad(coords2.longitude - coords1.longitude)
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRad(coords1.latitude)) *
Math.cos(toRad(coords2.latitude)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
return 12742 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
Here's another refactored answer in JavaScript:
getHaversineDistance = (firstLocation, secondLocation) => {
const earthRadius = 6371; // km
const diffLat = (secondLocation.lat-firstLocation.lat) * Math.PI / 180;
const diffLng = (secondLocation.lng-firstLocation.lng) * Math.PI / 180;
const arc = Math.cos(
firstLocation.lat * Math.PI / 180) * Math.cos(secondLocation.lat * Math.PI / 180)
* Math.sin(diffLng/2) * Math.sin(diffLng/2)
+ Math.sin(diffLat/2) * Math.sin(diffLat/2);
const line = 2 * Math.atan2(Math.sqrt(arc), Math.sqrt(1-arc));
const distance = earthRadius * line;
return distance;
}
const philly = { lat: 39.9526, lng: -75.1652 }
const nyc = { lat: 40.7128, lng: -74.0060 }
const losAngeles = { lat: 34.0522, lng: -118.2437 }
console.log(getHaversineDistance(philly, nyc)) //129.61277152662188
console.log(getHaversineDistance(philly, losAngeles)) //3843.4534005980404
This is a java implemetation of talkol's solution above. His or her solution worked very well for us. I'm not trying to answer the question, since the original question was for javascript. I'm just sharing our java implementation of the given javascript solution in case others find it of use.
// this was a pojo class we used internally...
public class GisPostalCode {
private String country;
private String postalCode;
private double latitude;
private double longitude;
// getters/setters, etc.
}
public static double distanceBetweenCoordinatesInMiles2(GisPostalCode c1, GisPostalCode c2) {
double lat2 = c2.getLatitude();
double lon2 = c2.getLongitude();
double lat1 = c1.getLatitude();
double lon1 = c1.getLongitude();
double R = 6371; // km
double x1 = lat2 - lat1;
double dLat = x1 * Math.PI / 180;
double x2 = lon2 - lon1;
double dLon = x2 * Math.PI / 180;
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1*Math.PI/180) * Math.cos(lat2*Math.PI/180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c;
// convert to miles
return d / 1.60934;
}
This is my code for the Haversine formula based off of this and the answer of this question:
$scope.getCoordDistance = function (myLat, myLon, locLat, locLon) {
var lat2 = 41.894993;
var lon2 = -88.459239;
var lat1 = $scope.locLat;
var lon1 = $scope.locLon;
var R = 3959;
var x1 = lat1 - lat2;
var dLat = x1 * Math.PI / 180;
var x2 = lon1 - lon2;
var dLon = x2 * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
d = R * c;
return d;
}
I tested this with 3 different locations an they are all way off, the first location says its 14790.7 miles away when it is actually 44.1 miles away, every location is off by a different amount. Some are off by a small amount, others a very large amount. Is something wrong with my math here? If not, why wont this code work correctly?
Here is a link to a plunk with my full project: http://plnkr.co/edit/nRQc7Ym0lsaK6jQwd626?p=preview Thanks in advanced for any help!!!
The actual calculation works out the distance. The problem is how you use it in your function.
You pass 4 parameters in function myLat, myLon, locLat, locLon and then don't use them. I assume that you are still calling function in a forEach loop. Try this
Outside forEach
var myLat = 41.894993;
var myLon = -88.459239;
Inside forEach
var locLat = $scope.locLat;
var locLon = $scope.locLon;
getCoordDistance(myLat, myLon, locLat, locLon)
etc.
Function
$scope.getCoordDistance = function (myLat, myLon, locLat, locLon) {
var R = 3959;
var x1 = lat1 - lat2;
var dLat = x1 * Math.PI / 180;
var x2 = lon1 - lon2;
var dLon = x2 * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
d = R * c;
return d;
}
I'm currently using the function below and it doesn't work properly. According to Google Maps, the distance between these coordinates (from 59.3293371,13.4877472 to 59.3225525,13.4619422) are 2.2 kilometres while the function returns 1.6 kilometres. How can I make this function return the correct distance?
function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
jsFiddle: http://jsfiddle.net/edgren/gAHJB/
What you're using is called the haversine formula, which calculates the distance between two points on a sphere as the crow flies. The Google Maps link you provided shows the distance as 2.2 km because it's not a straight line.
Wolfram Alpha is a great resource for doing geographic calculations, and also shows a distance of 1.652 km between these two points.
If you're looking for straight-line distance (as the crow files), your function is working correctly. If what you want is driving distance (or biking distance or public transportation distance or walking distance), you'll have to use a mapping API (Google or Bing being the most popular) to get the appropriate route, which will include the distance.
Incidentally, the Google Maps API provides a packaged method for spherical distance, in its google.maps.geometry.spherical namespace (look for computeDistanceBetween). It's probably better than rolling your own (for starters, it uses a more precise value for the Earth's radius).
For the picky among us, when I say "straight-line distance", I'm referring to a "straight line on a sphere", which is actually a curved line (i.e. the great-circle distance), of course.
I have written a similar equation before - tested it and also got 1.6 km.
Your google maps was showing the DRIVING distance.
Your function is calculating as the crow flies (straight line distance).
alert(calcCrow(59.3293371,13.4877472,59.3225525,13.4619422).toFixed(1));
//This function takes in latitude and longitude of two location and returns the distance between them as the crow flies (in km)
function calcCrow(lat1, lon1, lat2, lon2)
{
var R = 6371; // km
var dLat = toRad(lat2-lat1);
var dLon = toRad(lon2-lon1);
var lat1 = toRad(lat1);
var lat2 = toRad(lat2);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
// Converts numeric degrees to radians
function toRad(Value)
{
return Value * Math.PI / 180;
}
Derek's solution worked fine for me, and I've just simply converted it to PHP, hope it helps somebody out there !
function calcCrow($lat1, $lon1, $lat2, $lon2){
$R = 6371; // km
$dLat = toRad($lat2-$lat1);
$dLon = toRad($lon2-$lon1);
$lat1 = toRad($lat1);
$lat2 = toRad($lat2);
$a = sin($dLat/2) * sin($dLat/2) +sin($dLon/2) * sin($dLon/2) * cos($lat1) * cos($lat2);
$c = 2 * atan2(sqrt($a), sqrt(1-$a));
$d = $R * $c;
return $d;
}
// Converts numeric degrees to radians
function toRad($Value)
{
return $Value * pi() / 180;
}
Using Haversine formula, source of the code:
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::: :::
//::: This routine calculates the distance between two points (given the :::
//::: latitude/longitude of those points). It is being used to calculate :::
//::: the distance between two locations using GeoDataSource (TM) prodducts :::
//::: :::
//::: Definitions: :::
//::: South latitudes are negative, east longitudes are positive :::
//::: :::
//::: Passed to function: :::
//::: lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees) :::
//::: lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees) :::
//::: unit = the unit you desire for results :::
//::: where: 'M' is statute miles (default) :::
//::: 'K' is kilometers :::
//::: 'N' is nautical miles :::
//::: :::
//::: Worldwide cities and other features databases with latitude longitude :::
//::: are available at https://www.geodatasource.com :::
//::: :::
//::: For enquiries, please contact sales#geodatasource.com :::
//::: :::
//::: Official Web site: https://www.geodatasource.com :::
//::: :::
//::: GeoDataSource.com (C) All Rights Reserved 2018 :::
//::: :::
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
function distance(lat1, lon1, lat2, lon2, unit) {
if ((lat1 == lat2) && (lon1 == lon2)) {
return 0;
}
else {
var radlat1 = Math.PI * lat1/180;
var radlat2 = Math.PI * lat2/180;
var theta = lon1-lon2;
var radtheta = Math.PI * theta/180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = dist * 180/Math.PI;
dist = dist * 60 * 1.1515;
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist;
}
}
The sample code is licensed under LGPLv3.
Adding this for Node.JS users. You can use the haversine-distance module to do this so you won't need to handle the calculations on your own. See the npm page for more information.
To install:
npm install --save haversine-distance
You can use the module as follows:
var haversine = require("haversine-distance");
//First point in your haversine calculation
var point1 = { lat: 6.1754, lng: 106.8272 }
//Second point in your haversine calculation
var point2 = { lat: 6.1352, lng: 106.8133 }
var haversine_m = haversine(point1, point2); //Results in meters (default)
var haversine_km = haversine_m /1000; //Results in kilometers
console.log("distance (in meters): " + haversine_m + "m");
console.log("distance (in kilometers): " + haversine_km + "km");
I implemeneted this algorithm in typescript and ES6
export type Coordinate = {
lat: number;
lon: number;
};
get the distance between two points:
function getDistanceBetweenTwoPoints(cord1: Coordinate, cord2: Coordinate) {
if (cord1.lat == cord2.lat && cord1.lon == cord2.lon) {
return 0;
}
const radlat1 = (Math.PI * cord1.lat) / 180;
const radlat2 = (Math.PI * cord2.lat) / 180;
const theta = cord1.lon - cord2.lon;
const radtheta = (Math.PI * theta) / 180;
let dist =
Math.sin(radlat1) * Math.sin(radlat2) +
Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = (dist * 180) / Math.PI;
dist = dist * 60 * 1.1515;
dist = dist * 1.609344; //convert miles to km
return dist;
}
get the distance between an array of coordinates
export function getTotalDistance(coordinates: Coordinate[]) {
coordinates = coordinates.filter((cord) => {
if (cord.lat && cord.lon) {
return true;
}
});
let totalDistance = 0;
if (!coordinates) {
return 0;
}
if (coordinates.length < 2) {
return 0;
}
for (let i = 0; i < coordinates.length - 2; i++) {
if (
!coordinates[i].lon ||
!coordinates[i].lat ||
!coordinates[i + 1].lon ||
!coordinates[i + 1].lat
) {
totalDistance = totalDistance;
}
totalDistance =
totalDistance +
getDistanceBetweenTwoPoints(coordinates[i], coordinates[i + 1]);
}
return totalDistance.toFixed(2);
}
Calculate the Distance between Two Points in javascript
function distance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1/180
var radlat2 = Math.PI * lat2/180
var theta = lon1-lon2
var radtheta = Math.PI * theta/180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist
}
For more details refer this: Reference Link
Try this. It is in VB.net and you need to convert it to Javascript. This function accepts parameters in decimal minutes.
Private Function calculateDistance(ByVal long1 As String, ByVal lat1 As String, ByVal long2 As String, ByVal lat2 As String) As Double
long1 = Double.Parse(long1)
lat1 = Double.Parse(lat1)
long2 = Double.Parse(long2)
lat2 = Double.Parse(lat2)
'conversion to radian
lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0
long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0
lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0
long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0
' use to different earth axis length
Dim a As Double = 6378137.0 ' Earth Major Axis (WGS84)
Dim b As Double = 6356752.3142 ' Minor Axis
Dim f As Double = (a - b) / a ' "Flattening"
Dim e As Double = 2.0 * f - f * f ' "Eccentricity"
Dim beta As Double = (a / Math.Sqrt(1.0 - e * Math.Sin(lat1) * Math.Sin(lat1)))
Dim cos As Double = Math.Cos(lat1)
Dim x As Double = beta * cos * Math.Cos(long1)
Dim y As Double = beta * cos * Math.Sin(long1)
Dim z As Double = beta * (1 - e) * Math.Sin(lat1)
beta = (a / Math.Sqrt(1.0 - e * Math.Sin(lat2) * Math.Sin(lat2)))
cos = Math.Cos(lat2)
x -= (beta * cos * Math.Cos(long2))
y -= (beta * cos * Math.Sin(long2))
z -= (beta * (1 - e) * Math.Sin(lat2))
Return Math.Sqrt((x * x) + (y * y) + (z * z))
End Function
Edit
The converted function in javascript
function calculateDistance(lat1, long1, lat2, long2)
{
//radians
lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0;
long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0;
lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0;
long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0;
// use to different earth axis length
var a = 6378137.0; // Earth Major Axis (WGS84)
var b = 6356752.3142; // Minor Axis
var f = (a-b) / a; // "Flattening"
var e = 2.0*f - f*f; // "Eccentricity"
var beta = (a / Math.sqrt( 1.0 - e * Math.sin( lat1 ) * Math.sin( lat1 )));
var cos = Math.cos( lat1 );
var x = beta * cos * Math.cos( long1 );
var y = beta * cos * Math.sin( long1 );
var z = beta * ( 1 - e ) * Math.sin( lat1 );
beta = ( a / Math.sqrt( 1.0 - e * Math.sin( lat2 ) * Math.sin( lat2 )));
cos = Math.cos( lat2 );
x -= (beta * cos * Math.cos( long2 ));
y -= (beta * cos * Math.sin( long2 ));
z -= (beta * (1 - e) * Math.sin( lat2 ));
return (Math.sqrt( (x*x) + (y*y) + (z*z) )/1000);
}
I have written the function to find distance between two coordinates. It will return distance in meter.
function findDistance() {
var R = 6371e3; // R is earth’s radius
var lat1 = 23.18489670753479; // starting point lat
var lat2 = 32.726601; // ending point lat
var lon1 = 72.62524545192719; // starting point lon
var lon2 = 74.857025; // ending point lon
var lat1radians = toRadians(lat1);
var lat2radians = toRadians(lat2);
var latRadians = toRadians(lat2-lat1);
var lonRadians = toRadians(lon2-lon1);
var a = Math.sin(latRadians/2) * Math.sin(latRadians/2) +
Math.cos(lat1radians) * Math.cos(lat2radians) *
Math.sin(lonRadians/2) * Math.sin(lonRadians/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
console.log(d)
}
function toRadians(val){
var PI = 3.1415926535;
return val / 180.0 * PI;
}
Visit this address.
https://www.movable-type.co.uk/scripts/latlong.html
You can use this code:
JavaScript:
const R = 6371e3; // metres
const φ1 = lat1 * Math.PI/180; // φ, λ in radians
const φ2 = lat2 * Math.PI/180;
const Δφ = (lat2-lat1) * Math.PI/180;
const Δλ = (lon2-lon1) * Math.PI/180;
const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ/2) * Math.sin(Δλ/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
const d = R * c; // in metres
Great-circle distance - From chord length
Here's an elegant solution applying the strategy design pattern; I hope it's readable enough.
TwoPointsDistanceCalculatorStrategy.js:
module.exports = () =>
class TwoPointsDistanceCalculatorStrategy {
constructor() {}
calculateDistance({ point1Coordinates, point2Coordinates }) {}
};
GreatCircleTwoPointsDistanceCalculatorStrategy.js:
module.exports = ({ TwoPointsDistanceCalculatorStrategy }) =>
class GreatCircleTwoPointsDistanceCalculatorStrategy extends TwoPointsDistanceCalculatorStrategy {
constructor() {
super();
}
/**
* Following the algorithm documented here:
* https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulas
*
* #param {object} inputs
* #param {array} inputs.point1Coordinates
* #param {array} inputs.point2Coordinates
*
* #returns {decimal} distance in kelometers
*/
calculateDistance({ point1Coordinates, point2Coordinates }) {
const convertDegreesToRadians = require('../convert-degrees-to-radians');
const EARTH_RADIUS = 6371; // in kelometers
const [lat1 = 0, lon1 = 0] = point1Coordinates;
const [lat2 = 0, lon2 = 0] = point2Coordinates;
const radianLat1 = convertDegreesToRadians({ degrees: lat1 });
const radianLon1 = convertDegreesToRadians({ degrees: lon1 });
const radianLat2 = convertDegreesToRadians({ degrees: lat2 });
const radianLon2 = convertDegreesToRadians({ degrees: lon2 });
const centralAngle = _computeCentralAngle({
lat1: radianLat1, lon1: radianLon1,
lat2: radianLat2, lon2: radianLon2,
});
const distance = EARTH_RADIUS * centralAngle;
return distance;
}
};
/**
*
* #param {object} inputs
* #param {decimal} inputs.lat1
* #param {decimal} inputs.lon1
* #param {decimal} inputs.lat2
* #param {decimal} inputs.lon2
*
* #returns {decimal} centralAngle
*/
function _computeCentralAngle({ lat1, lon1, lat2, lon2 }) {
const chordLength = _computeChordLength({ lat1, lon1, lat2, lon2 });
const centralAngle = 2 * Math.asin(chordLength / 2);
return centralAngle;
}
/**
*
* #param {object} inputs
* #param {decimal} inputs.lat1
* #param {decimal} inputs.lon1
* #param {decimal} inputs.lat2
* #param {decimal} inputs.lon2
*
* #returns {decimal} chordLength
*/
function _computeChordLength({ lat1, lon1, lat2, lon2 }) {
const { sin, cos, pow, sqrt } = Math;
const ΔX = cos(lat2) * cos(lon2) - cos(lat1) * cos(lon1);
const ΔY = cos(lat2) * sin(lon2) - cos(lat1) * sin(lon1);
const ΔZ = sin(lat2) - sin(lat1);
const ΔXSquare = pow(ΔX, 2);
const ΔYSquare = pow(ΔY, 2);
const ΔZSquare = pow(ΔZ, 2);
const chordLength = sqrt(ΔXSquare + ΔYSquare + ΔZSquare);
return chordLength;
}
convert-degrees-to-radians.js:
module.exports = function convertDegreesToRadians({ degrees }) {
return degrees * Math.PI / 180;
};
This's following the Great-circle distance - From chord length, documented here.
You could use a module too:
Install:
$ npm install geolib
Usage:
import { getDistance } from 'geolib'
const distance = getDistance(
{ latitude: 51.5103, longitude: 7.49347 },
{ latitude: "51° 31' N", longitude: "7° 28' E" }
)
console.log(distance)
Documentation: https://www.npmjs.com/package/geolib
The answer from google
https://cloud.google.com/blog/products/maps-platform/how-calculate-distances-map-maps-javascript-api
And the check from three part.
https://www.distancefromto.net/
static distance({ x: x1, y: y1 }, { x: x2, y: y2 }) {
function toRadians(value) {
return value * Math.PI / 180
}
var R = 6371.0710
var rlat1 = toRadians(x1) // Convert degrees to radians
var rlat2 = toRadians(x2) // Convert degrees to radians
var difflat = rlat2 - rlat1 // Radian difference (latitudes)
var difflon = toRadians(y2 - y1) // Radian difference (longitudes)
return 2 * R * Math.asin(Math.sqrt(Math.sin(difflat / 2) * Math.sin(difflat / 2) + Math.cos(rlat1) * Math.cos(rlat2) * Math.sin(difflon / 2) * Math.sin(difflon / 2)))
}
As said before, your function is calculating a straight line distance to the destination point. If you want the driving distance/route, you can use Google Maps Distance Matrix Service:
getDrivingDistanceBetweenTwoLatLong(origin, destination) {
return new Observable(subscriber => {
let service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [new google.maps.LatLng(origin.lat, origin.long)],
destinations: [new google.maps.LatLng(destination.lat, destination.long)],
travelMode: 'DRIVING'
}, (response, status) => {
if (status !== google.maps.DistanceMatrixStatus.OK) {
console.log('Error:', status);
subscriber.error({error: status, status: status});
} else {
console.log(response);
try {
let valueInMeters = response.rows[0].elements[0].distance.value;
let valueInKms = valueInMeters / 1000;
subscriber.next(valueInKms);
subscriber.complete();
}
catch(error) {
subscriber.error({error: error, status: status});
}
}
});
});
}
I try to make the code a little bit understandable by naming the variables,
I hope this can help
function getDistanceFromLatLonInKm(point1, point2) {
const [lat1, lon1] = point1;
const [lat2, lon2] = point2;
const earthRadius = 6371;
const dLat = convertDegToRad(lat2 - lat1);
const dLon = convertDegToRad(lon2 - lon1);
const squarehalfChordLength =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(convertDegToRad(lat1)) * Math.cos(convertDegToRad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const angularDistance = 2 * Math.atan2(Math.sqrt(squarehalfChordLength), Math.sqrt(1 - squarehalfChordLength));
const distance = earthRadius * angularDistance;
return distance;
}
var phi = (90-lat)*(Math.PI/180);
var theta = (lng+180)*(Math.PI/180);
marker_mesh.position.x = ((rad) * Math.sin(phi)*Math.cos(theta));
marker_mesh.position.z = ((rad) * Math.sin(phi)*Math.sin(theta));
marker_mesh.position.y = ((rad) * Math.cos(phi));
given the above my marker is not translating into the correct position on a 3D sphere ... thoughts?
It is relatively close (on the same continent) but that close :\
given below ... it should be rendering in at
lat: 41.7307619 long: -71.276195
my globe has a boundRadius: 500px
the current result of the function is
x: -119.7801015013779
y: 332.8157297895266
z: 353.3927238766871
Your formula differs slightly from the geodetic to ECEF calculation. Refer to the formulas on Dr Math Latitude and Longitude, GPS Conversion and Wikipedia Geodetic to/from ECEF coordinates. This projects the latitude, longitude to a flattened sphere (i.e. the real Earth is not perfectly spherical).
var cosLat = Math.cos(lat * Math.PI / 180.0);
var sinLat = Math.sin(lat * Math.PI / 180.0);
var cosLon = Math.cos(lon * Math.PI / 180.0);
var sinLon = Math.sin(lon * Math.PI / 180.0);
var rad = 6378137.0;
var f = 1.0 / 298.257224;
var C = 1.0 / Math.sqrt(cosLat * cosLat + (1 - f) * (1 - f) * sinLat * sinLat);
var S = (1.0 - f) * (1.0 - f) * C;
var h = 0.0;
marker_mesh.position.x = (rad * C + h) * cosLat * cosLon;
marker_mesh.position.y = (rad * C + h) * cosLat * sinLon;
marker_mesh.position.z = (rad * S + h) * sinLat;
In your scenario, because it seems you're gunning for a perfect sphere, you will need to put f = 0.0 and rad = 500.0 instead. This will cause C and S to become 1.0, so, the simplified version of the formula reduces to:
var cosLat = Math.cos(lat * Math.PI / 180.0);
var sinLat = Math.sin(lat * Math.PI / 180.0);
var cosLon = Math.cos(lon * Math.PI / 180.0);
var sinLon = Math.sin(lon * Math.PI / 180.0);
var rad = 500.0;
marker_mesh.position.x = rad * cosLat * cosLon;
marker_mesh.position.y = rad * cosLat * sinLon;
marker_mesh.position.z = rad * sinLat;
N.B. I have not validated the syntax of the Java code examples.
To draw a circle on map I have a center GLatLng (A) and a radius (r) in meters.
Here's a diagram:
-----------
--/ \--
-/ \-
/ \
/ \
/ r \
| *-------------*
\ A / B
\ /
\ /
-\ /-
--\ /--
-----------
How to calculate the GLatLng at position B? Assuming that r is parallel to the equator.
Getting the radius when A and B is given is trivial using the GLatLng.distanceFrom() method - but doing it the other way around not so. Seems that I need to do some heavier math.
We will need a method that returns the destination point when given a bearing and the distance travelled from a source point. Luckily, there is a very good JavaScript implementation by Chris Veness at Calculate distance, bearing and more between Latitude/Longitude points.
The following has been adapted to work with the google.maps.LatLng class:
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
}
google.maps.LatLng.prototype.destinationPoint = function(brng, dist) {
dist = dist / 6371;
brng = brng.toRad();
var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) +
Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
Math.cos(lat1),
Math.cos(dist) - Math.sin(lat1) *
Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
You would simply use it as follows:
var pointA = new google.maps.LatLng(25.48, -71.26);
var radiusInKm = 10;
var pointB = pointA.destinationPoint(90, radiusInKm);
Here is a complete example using Google Maps API v3:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Geometry</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
}
google.maps.LatLng.prototype.destinationPoint = function(brng, dist) {
dist = dist / 6371;
brng = brng.toRad();
var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) +
Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
Math.cos(lat1),
Math.cos(dist) - Math.sin(lat1) *
Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
var pointA = new google.maps.LatLng(40.70, -74.00); // Circle center
var radius = 10; // 10km
var mapOpt = {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: pointA,
zoom: 10
};
var map = new google.maps.Map(document.getElementById("map"), mapOpt);
// Draw the circle
new google.maps.Circle({
center: pointA,
radius: radius * 1000, // Convert to meters
fillColor: '#FF0000',
fillOpacity: 0.2,
map: map
});
// Show marker at circle center
new google.maps.Marker({
position: pointA,
map: map
});
// Show marker at destination point
new google.maps.Marker({
position: pointA.destinationPoint(90, radius),
map: map
});
</script>
</body>
</html>
Screenshot:
UPDATE:
In reply to Paul's comment below, this is what happens when the circle wraps around one of the poles.
Plotting pointA near the north pole, with a radius of 1,000km:
var pointA = new google.maps.LatLng(85, 0); // Close to north pole
var radius = 1000; // 1000km
Screenshot for pointA.destinationPoint(90, radius):
To calculate a lat,long point at a given bearing and distance from another you can use google´s JavaScript implementation:
var pointA = new google.maps.LatLng(25.48, -71.26);
var distance = 10; // 10 metres
var bearing = 90; // 90 degrees
var pointB = google.maps.geometry.spherical.computeOffset(pointA, distance, bearing);
See https://developers.google.com/maps/documentation/javascript/reference#spherical
For documentation
If you are after the distance between 2 lat/lng points across the earths surface then you can find the javascript here:
http://www.movable-type.co.uk/scripts/latlong-vincenty.html
This is the same formula used in android API at android.location.Location::distanceTo
You can easily convert the code from javascript to java.
If you want to calculate the destination point given the start point, bearing and distance,
then you need this method:
http://www.movable-type.co.uk/scripts/latlong-vincenty-direct.html
Here are the formulae in java:
public class LatLngUtils {
/**
* #param lat1
* Initial latitude
* #param lon1
* Initial longitude
* #param lat2
* destination latitude
* #param lon2
* destination longitude
* #param results
* To be populated with the distance, initial bearing and final
* bearing
*/
public static void computeDistanceAndBearing(double lat1, double lon1,
double lat2, double lon2, double results[]) {
// Based on http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
// using the "Inverse Formula" (section 4)
int MAXITERS = 20;
// Convert lat/long to radians
lat1 *= Math.PI / 180.0;
lat2 *= Math.PI / 180.0;
lon1 *= Math.PI / 180.0;
lon2 *= Math.PI / 180.0;
double a = 6378137.0; // WGS84 major axis
double b = 6356752.3142; // WGS84 semi-major axis
double f = (a - b) / a;
double aSqMinusBSqOverBSq = (a * a - b * b) / (b * b);
double L = lon2 - lon1;
double A = 0.0;
double U1 = Math.atan((1.0 - f) * Math.tan(lat1));
double U2 = Math.atan((1.0 - f) * Math.tan(lat2));
double cosU1 = Math.cos(U1);
double cosU2 = Math.cos(U2);
double sinU1 = Math.sin(U1);
double sinU2 = Math.sin(U2);
double cosU1cosU2 = cosU1 * cosU2;
double sinU1sinU2 = sinU1 * sinU2;
double sigma = 0.0;
double deltaSigma = 0.0;
double cosSqAlpha = 0.0;
double cos2SM = 0.0;
double cosSigma = 0.0;
double sinSigma = 0.0;
double cosLambda = 0.0;
double sinLambda = 0.0;
double lambda = L; // initial guess
for (int iter = 0; iter < MAXITERS; iter++) {
double lambdaOrig = lambda;
cosLambda = Math.cos(lambda);
sinLambda = Math.sin(lambda);
double t1 = cosU2 * sinLambda;
double t2 = cosU1 * sinU2 - sinU1 * cosU2 * cosLambda;
double sinSqSigma = t1 * t1 + t2 * t2; // (14)
sinSigma = Math.sqrt(sinSqSigma);
cosSigma = sinU1sinU2 + cosU1cosU2 * cosLambda; // (15)
sigma = Math.atan2(sinSigma, cosSigma); // (16)
double sinAlpha = (sinSigma == 0) ? 0.0 : cosU1cosU2 * sinLambda
/ sinSigma; // (17)
cosSqAlpha = 1.0 - sinAlpha * sinAlpha;
cos2SM = (cosSqAlpha == 0) ? 0.0 : cosSigma - 2.0 * sinU1sinU2
/ cosSqAlpha; // (18)
double uSquared = cosSqAlpha * aSqMinusBSqOverBSq; // defn
A = 1 + (uSquared / 16384.0) * // (3)
(4096.0 + uSquared * (-768 + uSquared * (320.0 - 175.0 * uSquared)));
double B = (uSquared / 1024.0) * // (4)
(256.0 + uSquared * (-128.0 + uSquared * (74.0 - 47.0 * uSquared)));
double C = (f / 16.0) * cosSqAlpha * (4.0 + f * (4.0 - 3.0 * cosSqAlpha)); // (10)
double cos2SMSq = cos2SM * cos2SM;
deltaSigma = B
* sinSigma
* // (6)
(cos2SM + (B / 4.0)
* (cosSigma * (-1.0 + 2.0 * cos2SMSq) - (B / 6.0) * cos2SM
* (-3.0 + 4.0 * sinSigma * sinSigma)
* (-3.0 + 4.0 * cos2SMSq)));
lambda = L
+ (1.0 - C)
* f
* sinAlpha
* (sigma + C * sinSigma
* (cos2SM + C * cosSigma * (-1.0 + 2.0 * cos2SM * cos2SM))); // (11)
double delta = (lambda - lambdaOrig) / lambda;
if (Math.abs(delta) < 1.0e-12) {
break;
}
}
double distance = (b * A * (sigma - deltaSigma));
results[0] = distance;
if (results.length > 1) {
double initialBearing = Math.atan2(cosU2 * sinLambda, cosU1 * sinU2
- sinU1 * cosU2 * cosLambda);
initialBearing *= 180.0 / Math.PI;
results[1] = initialBearing;
if (results.length > 2) {
double finalBearing = Math.atan2(cosU1 * sinLambda, -sinU1 * cosU2
+ cosU1 * sinU2 * cosLambda);
finalBearing *= 180.0 / Math.PI;
results[2] = finalBearing;
}
}
}
/*
* Vincenty Direct Solution of Geodesics on the Ellipsoid (c) Chris Veness
* 2005-2012
*
* from: Vincenty direct formula - T Vincenty, "Direct and Inverse Solutions
* of Geodesics on the Ellipsoid with application of nested equations", Survey
* Review, vol XXII no 176, 1975 http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
*/
/**
* Calculates destination point and final bearing given given start point,
* bearing & distance, using Vincenty inverse formula for ellipsoids
*
* #param lat1
* start point latitude
* #param lon1
* start point longitude
* #param brng
* initial bearing in decimal degrees
* #param dist
* distance along bearing in metres
* #returns an array of the desination point coordinates and the final bearing
*/
public static void computeDestinationAndBearing(double lat1, double lon1,
double brng, double dist, double results[]) {
double a = 6378137, b = 6356752.3142, f = 1 / 298.257223563; // WGS-84
// ellipsiod
double s = dist;
double alpha1 = toRad(brng);
double sinAlpha1 = Math.sin(alpha1);
double cosAlpha1 = Math.cos(alpha1);
double tanU1 = (1 - f) * Math.tan(toRad(lat1));
double cosU1 = 1 / Math.sqrt((1 + tanU1 * tanU1)), sinU1 = tanU1 * cosU1;
double sigma1 = Math.atan2(tanU1, cosAlpha1);
double sinAlpha = cosU1 * sinAlpha1;
double cosSqAlpha = 1 - sinAlpha * sinAlpha;
double uSq = cosSqAlpha * (a * a - b * b) / (b * b);
double A = 1 + uSq / 16384
* (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
double sinSigma = 0, cosSigma = 0, deltaSigma = 0, cos2SigmaM = 0;
double sigma = s / (b * A), sigmaP = 2 * Math.PI;
while (Math.abs(sigma - sigmaP) > 1e-12) {
cos2SigmaM = Math.cos(2 * sigma1 + sigma);
sinSigma = Math.sin(sigma);
cosSigma = Math.cos(sigma);
deltaSigma = B
* sinSigma
* (cos2SigmaM + B
/ 4
* (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - B / 6
* cos2SigmaM * (-3 + 4 * sinSigma * sinSigma)
* (-3 + 4 * cos2SigmaM * cos2SigmaM)));
sigmaP = sigma;
sigma = s / (b * A) + deltaSigma;
}
double tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
double lat2 = Math.atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1,
(1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp));
double lambda = Math.atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1
* sinSigma * cosAlpha1);
double C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
double L = lambda
- (1 - C)
* f
* sinAlpha
* (sigma + C * sinSigma
* (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
double lon2 = (toRad(lon1) + L + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // normalise
// to
// -180...+180
double revAz = Math.atan2(sinAlpha, -tmp); // final bearing, if required
results[0] = toDegrees(lat2);
results[1] = toDegrees(lon2);
results[2] = toDegrees(revAz);
}
private static double toRad(double angle) {
return angle * Math.PI / 180;
}
private static double toDegrees(double radians) {
return radians * 180 / Math.PI;
}
}
The answer to this question and more can be found here: http://www.edwilliams.org/avform.htm
Javascript for many geodesic calculations (direct & inverse problems, area calculations, etc). is available at
http://geographiclib.sourceforge.net/scripts/geographiclib.js
Sample usage is shown in
http://geographiclib.sourceforge.net/scripts/geod-calc.html
An interface to google maps is provided at
http://geographiclib.sourceforge.net/scripts/geod-google.html
This includes plotting a geodesic (blue), geodesic circle (green) and the geodesic envelope (red).
Here's #Daniel Vassallo's answer adapter for Android (java) and using meters instead of km for distances:
private LatLng getDestinationPoint (LatLng pointStart, double bearing, double distance) {
distance = distance / 6371000;
bearing = getRad(bearing);
double lat1 = getRad(pointStart.latitude);
double lon1 = getRad(pointStart.longitude);
double lat2 = Math.asin(Math.sin(lat1) * Math.cos(distance) +
Math.cos(lat1) * Math.sin(distance) * Math.cos(bearing));
double lon2 = lon1 + Math.atan2(Math.sin(bearing) * Math.sin(distance) *
Math.cos(lat1),
Math.cos(distance) - Math.sin(lat1) *
Math.sin(lat2));
if (Double.isNaN(lat2) || Double.isNaN(lon2)) return null;
return new LatLng(getDeg(lat2), getDeg(lon2));
}
private double getRad(double degrees) {
return degrees * Math.PI / 180;
}
private double getDeg(double rad) {
return rad * 180 / Math.PI;
}