I tried using this:
function getRandomInRange(from, to, fixed) {
return parseFloat((Math.random() * (to - from) + from).toFixed(fixed));
}
var latLongPairs = 4;
for(var i =0; i<latLongPairs; i++) {
console.log(`${getRandomInRange(-180, 180, 3)}, ${getRandomInRange(-180, 180, 3)}`);
}
That's ok for random numbers like 39.21988,9.124741 but they might end up not valid coordinates. And I need 100 of them.
Your latitude range is incorrect - it should be ±90.
function getRandomInRange(from, to) {
return Math.random() * (to - from) + from;
}
const latLongPairs = 4;
for (let i = 0; i < latLongPairs; ++i) {
let lat = getRandomInRange(-90, 90);
let lon = getRandomInRange(-180, 180);
console.log(`${lat.toFixed(3)}, ${lon.toFixed(3)}`);
}
You might need to provide some initial Latitude and longitude with some radius (in meters)
var getRandomLocation = function(latitude, longitude, radiusInMeters) {
var getRandomCoordinates = function(radius, uniform) {
// Generate two random numbers
var a = Math.random(),
b = Math.random();
// Flip for more uniformity.
if (uniform) {
if (b < a) {
var c = b;
b = a;
a = c;
}
}
// It's all triangles.
return [
b * radius * Math.cos(2 * Math.PI * a / b),
b * radius * Math.sin(2 * Math.PI * a / b)
];
};
var randomCoordinates = getRandomCoordinates(radiusInMeters, true);
// Earths radius in meters via WGS 84 model.
var earth = 6378137;
// Offsets in meters.
var northOffset = randomCoordinates[0],
eastOffset = randomCoordinates[1];
// Offset coordinates in radians.
var offsetLatitude = northOffset / earth,
offsetLongitude = eastOffset / (earth * Math.cos(Math.PI * (latitude / 180)));
return `${latitude + (offsetLatitude * (180 / Math.PI))}, ${longitude + (offsetLongitude * (180 / Math.PI))}`
};
for (i = 0; i < 182; i++) {
console.log(getRandomLocation(41.8819, -87.6278, 50))
}
I want to plot a range of points on the lower left section (6 to 9 o'clock) of the perimeter of a circle. However, the starting point of rendering X,Y coordinates always begins at 3 o'clock.
!https://dl.dropboxusercontent.com/u/55849501/plotting-xy.png
Here is the rendering portion of my code:
var items = 5;
for(var i = 0; i < items; i++) {
var x = 96 + 100 * Math.cos(0.665 * Math.PI * i / items);
var y = 96 + 100 * Math.sin(0.665 * Math.PI * i / items);
$("#center").append("<div class='point' style='left:"+ x +"px;top:"+ y +"px'></div>");
}
And here is a jsfiddle of the code in action: http://jsfiddle.net/jE26S/198/
In summary:
I want the points to render starting at the 6 o'clock position instead of the 3 o'clock position.
What you are really doing here is interpolating between two values of theta. In your case, you want to start at Pi/2 and end at Pi. I took the liberty of re-writing your snippet using this interpolation paradigm. Also, you can adjust how far you want the dots/items away from the circle using outerCircleRadius.
var items = 5;
var startTheta = .5 * Math.PI;
var endTheta = 1 * Math.PI;
var outerCircleRadius = 112;
var cx = 90;
var cy = 90;
for(var i = 0; i < items; i++) {
var theta = startTheta + (endTheta - startTheta) * i / (items - 1)
var x = cx + outerCircleRadius * Math.cos(theta);
var y = cy + outerCircleRadius * Math.sin(theta);
$("#center").append("<div class='point' style='left:"+ x +"px;top:"+ y +"px'></div>");
}
Something like this?
var x = 86 + 100 * Math.cos(0.665 * Math.PI * (items-1+i-0.5) / items);
var y = 96 + 100 * Math.sin(0.665 * Math.PI * (items-1+i-0.5) / items);
Everything in Richard Shurtz's answer, except for the "items - 1" in the first line in the loop.
This worked for any number of items:
var items = 5;
var startTheta = .5 * Math.PI;
var endTheta = 1 * Math.PI;
var outerCircleRadius = 112;
var cx = 90;
var cy = 90;
for(var i = 0; i < items; i++) {
var theta = startTheta + (endTheta - startTheta) * i / items
var x = cx + outerCircleRadius * Math.cos(theta);
var y = cy + outerCircleRadius * Math.sin(theta);
$("#center").append("<div class='point' style='left:"+ x +"px;top:"+ y +"px'></div>");
}
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;
}
i have a polyine which i have drawn with latlngs obtained from google maps directions service.
Now i want to find a point on the polyline that is closest to a given point.
The obvious way (to me) is to kind of loop through all the points in the polyline and find the distance between them and the given point, however this is inefficient because the points on the polyline can potentially be large.
I would be glad to hear any alternatives of doing this.
Thanks in advance.
I needed a cleaner version that was ported to V3, so here it is:
/**
* Snap marker to closest point on a line.
*
* Based on Distance to line example by
* Marcelo, maps.forum.nu - http://maps.forum.nu/gm_mouse_dist_to_line.html
* Then
* # work of Björn Brala - Swis BV who wrapped the algorithm in a class operating on GMap Objects
* And now
* Bill Chadwick, who factored the basic algorithm out of the class (removing much intermediate storage of results)
* and added distance along line to nearest point calculation
* Followed by
* Robert Crowe, who ported it to v3 of the Google Maps API and factored out the marker to make it more general.
*
* Usage:
*
* Create the class
* var oSnap = new cSnapToRoute();
*
* Initialize the subjects
* oSnap.init(oMap, oPolyline);
*
**/
function cSnapToRoute() {
this.routePoints = Array();
this.routePixels = Array();
this._oMap;
this._oPolyline;
/**
* #desc Initialize the objects.
* #param Map object
* #param GPolyline object - the 'route'
**/
this.init = function (oMap, oPolyline) {
this._oMap = oMap;
this._oPolyline = oPolyline;
this.loadRouteData(); // Load needed data for point calculations
}
/**
* #desc internal use only, Load route points into RoutePixel array for calculations, do this whenever zoom changes
**/
this.loadRouteData = function () {
this.routePixels = new Array();
var proj = this._oMap.getProjection();
for (var i = 0; i < this._oPolyline.getPath().getLength(); i++) {
var Px = proj.fromLatLngToPoint(this._oPolyline.getPath().getAt(i));
this.routePixels.push(Px);
}
}
/**
* #desc Get closest point on route to test point
* #param GLatLng() the test point
* #return new GLatLng();
**/
this.getClosestLatLng = function (latlng) {
var r = this.distanceToLines(latlng);
var proj = this._oMap.getProjection();
return proj.fromPointToLatLng(new google.maps.Point(r.x, r.y));
}
/**
* #desc Get distance along route in meters of closest point on route to test point
* #param GLatLng() the test point
* #return distance in meters;
**/
this.getDistAlongRoute = function (latlng) {
var r = this.distanceToLines(latlng);
return this.getDistToLine(r.i, r.fTo);
}
/**
* #desc internal use only, gets test point xy and then calls fundamental algorithm
**/
this.distanceToLines = function (thisLatLng) {
var tm = this._oMap;
var proj = this._oMap.getProjection();
var thisPx = proj.fromLatLngToPoint(thisLatLng);
var routePixels = this.routePixels;
return getClosestPointOnLines(thisPx, routePixels);
}
/**
* #desc internal use only, find distance along route to point nearest test point
**/
this.getDistToLine = function (iLine, fTo) {
var routeOverlay = this._oPolyline;
var d = 0;
for (var n = 1 ; n < iLine ; n++) {
d += routeOverlay.getPath().getAt(n - 1).distanceFrom(routeOverlay.getPath().getAt(n));
}
d += routeOverlay.getPath().getAt(iLine - 1).distanceFrom(routeOverlay.getPath().getAt(iLine)) * fTo;
return d;
}
}
/* desc Static function. Find point on lines nearest test point
test point pXy with properties .x and .y
lines defined by array aXys with nodes having properties .x and .y
return is object with .x and .y properties and property i indicating nearest segment in aXys
and property fFrom the fractional distance of the returned point from aXy[i-1]
and property fTo the fractional distance of the returned point from aXy[i] */
function getClosestPointOnLines(pXy, aXys) {
var minDist;
var fTo;
var fFrom;
var x;
var y;
var i;
var dist;
if (aXys.length > 1) {
for (var n = 1 ; n < aXys.length ; n++) {
if (aXys[n].x != aXys[n - 1].x) {
var a = (aXys[n].y - aXys[n - 1].y) / (aXys[n].x - aXys[n - 1].x);
var b = aXys[n].y - a * aXys[n].x;
dist = Math.abs(a * pXy.x + b - pXy.y) / Math.sqrt(a * a + 1);
}
else
dist = Math.abs(pXy.x - aXys[n].x)
// length^2 of line segment
var rl2 = Math.pow(aXys[n].y - aXys[n - 1].y, 2) + Math.pow(aXys[n].x - aXys[n - 1].x, 2);
// distance^2 of pt to end line segment
var ln2 = Math.pow(aXys[n].y - pXy.y, 2) + Math.pow(aXys[n].x - pXy.x, 2);
// distance^2 of pt to begin line segment
var lnm12 = Math.pow(aXys[n - 1].y - pXy.y, 2) + Math.pow(aXys[n - 1].x - pXy.x, 2);
// minimum distance^2 of pt to infinite line
var dist2 = Math.pow(dist, 2);
// calculated length^2 of line segment
var calcrl2 = ln2 - dist2 + lnm12 - dist2;
// redefine minimum distance to line segment (not infinite line) if necessary
if (calcrl2 > rl2)
dist = Math.sqrt(Math.min(ln2, lnm12));
if ((minDist == null) || (minDist > dist)) {
if (calcrl2 > rl2) {
if (lnm12 < ln2) {
fTo = 0;//nearer to previous point
fFrom = 1;
}
else {
fFrom = 0;//nearer to current point
fTo = 1;
}
}
else {
// perpendicular from point intersects line segment
fTo = ((Math.sqrt(lnm12 - dist2)) / Math.sqrt(rl2));
fFrom = ((Math.sqrt(ln2 - dist2)) / Math.sqrt(rl2));
}
minDist = dist;
i = n;
}
}
var dx = aXys[i - 1].x - aXys[i].x;
var dy = aXys[i - 1].y - aXys[i].y;
x = aXys[i - 1].x - (dx * fTo);
y = aXys[i - 1].y - (dy * fTo);
}
return { 'x': x, 'y': y, 'i': i, 'fTo': fTo, 'fFrom': fFrom };
}
See Bill Chadwick's example here:
http://www.bdcc.co.uk/Gmaps/BdccGmapBits.htm
above example ported to v3 (code at bottom of this answer)
on his page under:
DISTANCE POINT TO POLYLINE OR POLYGON
from that post:
There is a similar, better demo here http://wtp2.appspot.com/cSnapToRouteDemo.html
It is finding the closest point on the line to the mouse. Also note that it is a Google Maps API v2 example (but the principle with v3 would be the same).
// Code to find the distance in metres between a lat/lng point and a polyline of lat/lng points
// All in WGS84. Free for any use.
//
// Bill Chadwick 2007
// updated to Google Maps API v3, Lawrence Ross 2014
// Construct a bdccGeo from its latitude and longitude in degrees
function bdccGeo(lat, lon)
{
var theta = (lon * Math.PI / 180.0);
var rlat = bdccGeoGeocentricLatitude(lat * Math.PI / 180.0);
var c = Math.cos(rlat);
this.x = c * Math.cos(theta);
this.y = c * Math.sin(theta);
this.z = Math.sin(rlat);
}
bdccGeo.prototype = new bdccGeo();
// internal helper functions =========================================
// Convert from geographic to geocentric latitude (radians).
function bdccGeoGeocentricLatitude(geographicLatitude)
{
var flattening = 1.0 / 298.257223563;//WGS84
var f = (1.0 - flattening) * (1.0 - flattening);
return Math.atan((Math.tan(geographicLatitude) * f));
}
// Returns the two antipodal points of intersection of two great
// circles defined by the arcs geo1 to geo2 and
// geo3 to geo4. Returns a point as a Geo, use .antipode to get the other point
function bdccGeoGetIntersection( geo1, geo2, geo3, geo4)
{
var geoCross1 = geo1.crossNormalize(geo2);
var geoCross2 = geo3.crossNormalize(geo4);
return geoCross1.crossNormalize(geoCross2);
}
//from Radians to Meters
function bdccGeoRadiansToMeters(rad)
{
return rad * 6378137.0; // WGS84 Equatorial Radius in Meters
}
//from Meters to Radians
function bdccGeoMetersToRadians(m)
{
return m / 6378137.0; // WGS84 Equatorial Radius in Meters
}
// properties =================================================
bdccGeo.prototype.getLatitudeRadians = function()
{
return (bdccGeoGeographicLatitude(Math.atan2(this.z,
Math.sqrt((this.x * this.x) + (this.y * this.y)))));
}
bdccGeo.prototype.getLongitudeRadians = function()
{
return (Math.atan2(this.y, this.x));
}
bdccGeo.prototype.getLatitude = function()
{
return this.getLatitudeRadians() * 180.0 / Math.PI;
}
bdccGeo.prototype.getLongitude = function()
{
return this.getLongitudeRadians() * 180.0 / Math.PI ;
}
// Methods =================================================
//Maths
bdccGeo.prototype.dot = function( b)
{
return ((this.x * b.x) + (this.y * b.y) + (this.z * b.z));
}
//More Maths
bdccGeo.prototype.crossLength = function( b)
{
var x = (this.y * b.z) - (this.z * b.y);
var y = (this.z * b.x) - (this.x * b.z);
var z = (this.x * b.y) - (this.y * b.x);
return Math.sqrt((x * x) + (y * y) + (z * z));
}
//More Maths
bdccGeo.prototype.scale = function( s)
{
var r = new bdccGeo(0,0);
r.x = this.x * s;
r.y = this.y * s;
r.z = this.z * s;
return r;
}
// More Maths
bdccGeo.prototype.crossNormalize = function( b)
{
var x = (this.y * b.z) - (this.z * b.y);
var y = (this.z * b.x) - (this.x * b.z);
var z = (this.x * b.y) - (this.y * b.x);
var L = Math.sqrt((x * x) + (y * y) + (z * z));
var r = new bdccGeo(0,0);
r.x = x / L;
r.y = y / L;
r.z = z / L;
return r;
}
// point on opposite side of the world to this point
bdccGeo.prototype.antipode = function()
{
return this.scale(-1.0);
}
//distance in radians from this point to point v2
bdccGeo.prototype.distance = function( v2)
{
return Math.atan2(v2.crossLength(this), v2.dot(this));
}
//returns in meters the minimum of the perpendicular distance of this point from the line segment geo1-geo2
//and the distance from this point to the line segment ends in geo1 and geo2
bdccGeo.prototype.distanceToLineSegMtrs = function(geo1, geo2)
{
//point on unit sphere above origin and normal to plane of geo1,geo2
//could be either side of the plane
var p2 = geo1.crossNormalize(geo2);
// intersection of GC normal to geo1/geo2 passing through p with GC geo1/geo2
var ip = bdccGeoGetIntersection(geo1,geo2,this,p2);
//need to check that ip or its antipode is between p1 and p2
var d = geo1.distance(geo2);
var d1p = geo1.distance(ip);
var d2p = geo2.distance(ip);
//window.status = d + ", " + d1p + ", " + d2p;
if ((d >= d1p) && (d >= d2p))
return bdccGeoRadiansToMeters(this.distance(ip));
else
{
ip = ip.antipode();
d1p = geo1.distance(ip);
d2p = geo2.distance(ip);
}
if ((d >= d1p) && (d >= d2p))
return bdccGeoRadiansToMeters(this.distance(ip));
else
return bdccGeoRadiansToMeters(Math.min(geo1.distance(this),geo2.distance(this)));
}
// distance in meters from GLatLng point to GPolyline or GPolygon poly
function bdccGeoDistanceToPolyMtrs(poly, point)
{
var d = 999999999;
var i;
var p = new bdccGeo(point.lat(),point.lng());
for(i=0; i<(poly.getPath().getLength()-1); i++)
{
var p1 = poly.getPath().getAt(i);
var l1 = new bdccGeo(p1.lat(),p1.lng());
var p2 = poly.getPath().getAt(i+1);
var l2 = new bdccGeo(p2.lat(),p2.lng());
var dp = p.distanceToLineSegMtrs(l1,l2);
if(dp < d)
d = dp;
}
return d;
}
// get a new GLatLng distanceMeters away on the compass bearing azimuthDegrees
// from the GLatLng point - accurate to better than 200m in 140km (20m in 14km) in the UK
function bdccGeoPointAtRangeAndBearing (point, distanceMeters, azimuthDegrees)
{
var latr = point.lat() * Math.PI / 180.0;
var lonr = point.lng() * Math.PI / 180.0;
var coslat = Math.cos(latr);
var sinlat = Math.sin(latr);
var az = azimuthDegrees* Math.PI / 180.0;
var cosaz = Math.cos(az);
var sinaz = Math.sin(az);
var dr = distanceMeters / 6378137.0; // distance in radians using WGS84 Equatorial Radius
var sind = Math.sin(dr);
var cosd = Math.cos(dr);
return new google.maps.LatLng(Math.asin((sinlat * cosd) + (coslat * sind * cosaz)) * 180.0 / Math.PI,
(Math.atan2((sind * sinaz), (coslat * cosd) - (sinlat * sind * cosaz)) + lonr) * 180.0 / Math.PI);
}
I do not think you can avoid checking all the points.
What if the not checked point is the nearest one?
If you have to do this operation many times, you can choose a data structure that is optimized for such a search, quadtree for example.
Note that you should not use lat lng as Descartes coordinates.
See also Finding nearest point in an efficient way
That is for the 2D plane, and not for lat lng, but you can approximate: https://stackoverflow.com/a/16271669/59019
Inspired by jmihalicza's answer, i came up with this function to find the closest point in an array of LatLngs to a given LatLng.
function closest takes a LatLng(llng) and an array of LatLngs (listData) and finds the distance between each latlng in the array and the given latlng, it then finds the least distance and returns the Latlng from the list which provided that distance.
function closest(llng, listData) {
var arr = listData;
var pnt = llng;
var distArr = [];
var dist = google.maps.geometry.spherical.computeDistanceBetween;
for (index in arr)
distArr.push([arr[index], dist(pnt, arr[index])]);
return distArr.sort(function(a,b){
return a[1]-b[1];
})[0][0];
}
EDIT
If you don't have access to the array of LatLngs which make up the polyline, but have access to the polyline itself, you can use polyline's getPath method to get the path which is an MVC array so you can use .getArray() to return an array of LatLngs to use with the above function (closest).
I am trying to draw a circle on a CloudMade map. The center of the circle is expressed in Lat/Lng, while the radius is in meters. Here following is the JavaScript I use, but some tests seem to indictae that the conversion I'm using for the radius gives me a too short radius. Does somebody understand what I', doing wrong?
function DrawCircle (center, radius)
{
var circlePoints = Array();
with (Math)
{
var d = radius/6371000; // radians
var lat1 = (PI/180) * center.lat(); // radians
var lng1 = (PI/180) * center.lng(); // radians
for (var a = 0; a <= 360; a++)
{
var tc = (PI/180) * a;
var y = asin(sin(lat1) * cos(d) + cos(lat1) * sin(d) * cos(tc));
var dlng = atan2(sin(tc) * sin(d) * cos(lat1), cos(d) - sin(lat1) * sin(y));
var x = ((lng1 - dlng + PI) % (2 * PI)) - PI ; // MOD function
var point = new CM.LatLng(parseFloat(y * (180/PI)), parseFloat(x * (180/PI)));
circlePoints.push(point);
}
circle = new CM.Polygon(circlePoints, circleBorderColor, circleBorderWidth, circleBorderOpacity, circleFillColor, circleFillOpacity);
map.addOverlay(circle);
}
}