Created
July 15, 2014 16:54
-
-
Save jczaplew/db66cd9563805e05c7f7 to your computer and use it in GitHub Desktop.
Point on line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Largely borrowed from the excellent Turf.js | |
https://github.com/Turfjs/turf-distance/blob/master/index.js */ | |
function distance(a, b) { | |
function toRadians(degree) { | |
return degree * Math.PI / 180; | |
} | |
var R = 57.2957795, | |
dLat = toRadians(b.lat - a.lat), | |
dLon = toRadians(b.lng - a.lng); | |
var x = | |
Math.sin(dLat/2) * Math.sin(dLat/2) + | |
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(toRadians(a.lat)) * Math.cos(toRadians(b.lat)); | |
var c = 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1 - x)); | |
// Return distance in degrees | |
return R * c; | |
} | |
// Is c beween a and b? | |
function isBetween(a, b, c) { | |
var epsilon = this._distance(a, b); | |
var crossProduct = (c.lat - a.lat) * (b.lng - a.lng) - (c.lng - a.lng) * (b.lat - a.lat); | |
if (Math.abs(crossProduct) > epsilon) { | |
return false; | |
} | |
var dotProduct = (c.lng - a.lng) * (b.lng - a.lng) + (c.lat - a.lat) * (b.lat - a.lat); | |
if (dotProduct < 0) { | |
return false; | |
} | |
var squaredLengthBA = (b.lng - a.lng) * (b.lng - a.lng) + (b.lat - a.lat) * (b.lat - a.lat); | |
if (dotProduct > squaredLengthBA) { | |
return false; | |
} | |
return true; | |
} |
var slopeDiff = (c.lng - a.lng) / (c.lat - a.lat) - (b.lng - a.lng) / (b.lat - a.lat);
if (Math.abs(slopeDiff ) > epsilon) {
return false;
}
if (Math.pow((Math.pow((c.lng - a.lng),2) + Math.pow((c.lat - a.lat),2)),0.5) > Math.pow(( Math.pow((b.lng - a.lng), 2) + Math.pow((b.lat - a.lat), 2)), 0.5)) {
return false;
}
return true
Starts with this to get rid of div/0 cases
if (a.lat == b.lat){
if(a.lat == c.lat){
if(Math.abs(a.lng - c.lng) < Math.abs(a.lng - b.lng)){
return true
}
}
return false;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var slopeDiff = (c.lng - a.lng) / (c.lat - a.lat) - (b.lng - a.lng) / (b.lat - a.lat);
if (Math.abs(slopeDiff ) > epsilon) { #where epsilon is some small number, e.g. 1e-3
return false;
}
Then, just check the following
if ((c.lng - a.lng)^2 + (c.lat - a.lat)^2)^(1/2) > ((b.lng - a.lng)^2 + (b.lat - a.lat)^2)^(1/2) {
return false;
}
Done, return true