Inverse of local coordinate system to latitude and longitude - javascript

I have a function to convert latitude and longitude to localCordinateSystem
const EARTH_RADIUS_KM = 6371.0;
const distanceInMeters = (lat1, lon1, lat2, lon2) => {
const lonDiff = toRadians(lon2 - lon1);
const latDiff = toRadians(lat2 - lat1);
const a = Math.pow(Math.sin(latDiff / 2), 2) + Math.cos(toRadians(lat1)) *
Math.cos(toRadians(lat2)) * Math.pow(Math.sin(lonDiff / 2), 2);
const angle = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return angle * EARTH_RADIUS_KM * 1000.0;
};
const localCoordinateSystem = (lat, lon, originLat, originLon, radius) => {
let latDist = distanceInMeters(originLat, originLon, lat, originLon);
let lonDist = distanceInMeters(originLat, originLon, originLat, lon);
if (lat < originLat) latDist *= -1;
if (lon < originLon) lonDist *= -1;
return {
x: parseFloat(latDist) + parseFloat(radius),
y: parseFloat(lonDist) + parseFloat(radius),
};
};
If you see the function localCoordinateSystem takes lat, lon, originLat, originLon and radius and returns x and y.
But now I want a function that takes x, y, originLat, originLon and radius and returns lat and lon.

Related

Find the nearest friends from my current location

I want to find my friends by taking their location from their mobile phone who are near to me from my current location.
For example in my code below I have var cities, If I put 3,4 numbers of my friends so I can do this? Or can I do this making some other changes? Is it possible?
// Get User's Coordinate from their Browser
window.onload = function () {
// HTML5/W3C Geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(UserLocation);
}
// Default to Washington, DC
else
NearestCity(38.8951, -77.0367);
}
// Callback function for asynchronous call to HTML5 geolocation
function UserLocation(position) {
NearestCity(position.coords.latitude, position.coords.longitude);
}
// Convert Degress to Radians
function Deg2Rad(deg) {
return deg * Math.PI / 180;
}
function PythagorasEquirectangular(lat1, lon1, lat2, lon2) {
lat1 = Deg2Rad(lat1);
lat2 = Deg2Rad(lat2);
lon1 = Deg2Rad(lon1);
lon2 = Deg2Rad(lon2);
var R = 6371; // km
var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
var y = (lat2 - lat1);
var d = Math.sqrt(x * x + y * y) * R;
return d;
}
var lat = 20; // user's latitude
var lon = 40; // user's longitude
var cities = [
["city1", 10, 50, "blah"],
["city2", 40, 60, "blah"],
["city3", 25, 10, "blah"],
["city4", 5, 80, "blah"]
];
function NearestCity(latitude, longitude) {
var mindif = 99999;
var closest;
for (index = 0; index < cities.length; ++index) {
var dif = PythagorasEquirectangular(latitude, longitude, cities[index]
[1], cities[index][2]);
if (dif < mindif) {
closest = index;
mindif = dif;
}
}
// echo the nearest city
alert(cities[closest]);
}
I suggest using GeoFire for that purpose it is from firebase and has Geographical based queries and can do what you want in an easy way

how to calculate location different from distance

i am new in gis. I am working in JavaScript.
suppose there is center latlong. another point is target(latlong) in n miters far from center. how to calculate this location difference(center - latlong) from center and n in miter.
guys please help me.
lets consider earth is properly spherical.
function distance(lat1, lon1, lat2, lon2) {
var radius = 6371e3; // meters
var dLon = gis.toRad(lon2 - lon1),
lat1 = gis.toRad(lat1),
lat2 = gis.toRad(lat2),
distance = Math.acos(Math.sin(lat1) * Math.sin(lat2) +
Math.cos(lat1) * Math.cos(lat2) * Math.cos(dLon)) * radius;
return distance;
}
above javascript function is for calculating distance,
function(lat, long, distance){
//can i calculate lat_difference, long difference
}
here is your code:-
<script>
Math.radians = function(degrees) {
return degrees * Math.PI / 180;
};
function calculateDistance(lat,lon,lat_center,lon_center){
var distance = ( 6371 * Math.acos( Math.cos( Math.radians(lat) ) * Math.cos( Math.radians( lat_center ) )
* Math.cos( Math.radians( lon_center ) - Math.radians(lon) ) + Math.sin( Math.radians(lat) ) * Math.sin(Math.radians(lat_center)) ) )*1000;
console.log(distance+" meter");
return distance;
}
var lat = '38.898556';
var lon = '-77.037852';
var lat_center = '38.897147';
var lon_center = '-77.043934';
calculateDistance(lat,lon,lat_center,lon_center);//will return 549 meter
//for getting lat and lon from a distance from a given point
//lat1 = latitude of start point in degrees
//long1 = longitude of start point in degrees
//d = distance in KM
//angle = bearing in degrees
function get_gps_distance(lat1,long1,d,angle)
{
//# Earth Radious in KM
var R = 6378.14;
//# Degree to Radian
var latitude1 = lat1 * (Math.PI/180);
var longitude1 = long1 * (Math.PI/180);
brng = angle * (Math.PI/180);
latitude2 = Math.asin(Math.sin(latitude1)*Math.cos(d/R) + Math.cos(latitude1)*Math.sin(d/R)*Math.cos(brng));
longitude2 = longitude1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(latitude1),Math.cos(d/R)-Math.sin(latitude1)*Math.sin(latitude2));
// # back to degrees
latitude2 = latitude2 * (180/Math.PI);
longitude2 = longitude2 * (180/Math.PI);
// # 6 decimal for Leaflet and other system compatibility
lat2 = latitude2;
long2 =longitude2;
var tab = {};
// Push in array and get back
tab[0] = lat2;
tab[1] = long2;
return tab;
}
get_gps_distance('38.898556','-77.037852',.549,90);
</script>

Google map API v.3 find nearest point from one point to point on polyline

I`ve got a map with a polyline. The server will responds me with a LatLng point on a map. I need to check if the point from the server situated on a polyline edge. If not, i need to find the nearest point on the polyline and place a marker on the nearest point on the polyline. For example, if the server responds me with a point A, i need to place a marker to a point B.
I find a good library http://wtp2.appspot.com/cSnapToRouteDemo.html, but this library is for Google API ver. 2, and i'm using Google API ver. 3. Is there any alternative for Google API ver. 3 ? Thank's.
Found an easier solution.Using turf.js.Just use your polyline coordinates to create turf line and marker position for creating turf point.
then;
var line = turf.lineString(Your polyline coordinates in GeoJson array);
var pt = turf.point([Marker_Lon, Marker_Lat]);
var snapped = turf.pointOnLine(line, pt);
var pstnOnLine = { lat: snapped.geometry.coordinates[1], lng: snapped.geometry.coordinates[0] };
var distToLine = snapped.properties.dist
This way you can calculate the distance and coordinates on your polyline easily.
You can find out more from Turf website.
The Google Maps Javascript API has a Geometry library.
The Geometry library has a isLocationOnEdge function. See the documentation.
To determine whether a point falls on or near a polyline, or on or near the edge of a polygon, pass the point, the polyline/polygon, and optionally a tolerance value in degrees to google.maps.geometry.poly.isLocationOnEdge(). The function returns true if the distance between the point and the closest point on the line or edge falls within the specified tolerance. The default tolerance value is 10-9 degrees.
You must include the library this way:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">
</script>
And if you need more than one library, for example:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry,places">
</script>
Full documentation is here.
If you need to find the point on the Polyline, you can use this ported to v3 version of the library you mentioned in your question:
var mapRoute;
var rtPoints;
var centerMAP = new google.maps.LatLng(-7.402438, 110.446957);
function gLatLngFromEN(e, n) {
var ogbLL = NEtoLL(e, n);
var pc = OGBToWGS84(ogbLL.lat, ogbLL.lon, 0);
return new google.maps.LatLng(pc.lat, pc.lon);
}
function routeMap() {
mapRoute = new google.maps.Map(document.getElementById('mapRoute'), {
center: centerMAP,
zoom: 14,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
mapRoute.setCenter(gLatLngFromEN(469000, 169000), 13);
var rtPoints = new Array();
rtPoints.push(gLatLngFromEN(468000, 168000));
rtPoints.push(gLatLngFromEN(468000, 170000));
rtPoints.push(gLatLngFromEN(470000, 170000));
rtPoints.push(gLatLngFromEN(470000, 168000));
var rtPoly = new google.maps.Polyline({
path: rtPoints,
strokeColor: "#0000FF",
strokeWeight: 3,
map: mapRoute
});
var container = document.createElement("div");
container.style.fontFamily = 'Arial';
container.style.fontSize = 'XX-Small';
var ptr = document.createElement("INPUT");
ptr.style.width = "100px";
ptr.type = "Text";
ptr.readOnly = true;
ptr.id = "distPtr";
container.appendChild(ptr);
document.getElementById("control").appendChild(container);
google.maps.event.addListener(mapRoute, 'mousemove', function (point) {
document.getElementById('distPtr').value = Math.round(bdccGeoDistanceToPolyMtrs(rtPoly, point.latLng));
});
}
google.maps.event.addDomListener(window, 'load', routeMap);
// 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));
}
// Convert from geocentric to geographic latitude (radians)
function bdccGeoGeographicLatitude (geocentricLatitude)
{
var flattening = 1.0 / 298.257223563;//WGS84
var f = (1.0 - flattening) * (1.0 - flattening);
return Math.atan(Math.tan(geocentricLatitude) / 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);
}
Credits to Bill Chadwick 2007 and Lawrence Ross 2014 for the v3 version. And #geocodezip for finding it.
JSFiddle demo

Geolocation closest location(lat, long) from my position

I want to show specific information depending on where i am.
I have five cities with different information, and i want to show that city(information) that i'm closest to.
How to i do that the simplest way, using javascript.
Ex.
If i store the cities lat, long in an array
var cities = [
['new york', '111111', '222222', 'blablabla']
['boston', '111111', '222222', 'blablabla']
['seattle', '111111', '222222', 'blablabla']
['london', '111111', '222222', 'blablabla']
]
And with my current location(lat, long) i want the city that i'm closet to.
Here is a basic code example using HTML5 geolocation to get the user's position. It then calls NearestCity() and calculates the distance (km) from the location to each city. I passed on using the Haversine formulae and instead used the simpler Pythagoras formulae and an equirectangular projection to adjust for the curvature in longitude lines.
// Get User's Coordinate from their Browser
window.onload = function() {
// HTML5/W3C Geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(UserLocation);
}
// Default to Washington, DC
else
NearestCity(38.8951, -77.0367);
}
// Callback function for asynchronous call to HTML5 geolocation
function UserLocation(position) {
NearestCity(position.coords.latitude, position.coords.longitude);
}
// Convert Degress to Radians
function Deg2Rad(deg) {
return deg * Math.PI / 180;
}
function PythagorasEquirectangular(lat1, lon1, lat2, lon2) {
lat1 = Deg2Rad(lat1);
lat2 = Deg2Rad(lat2);
lon1 = Deg2Rad(lon1);
lon2 = Deg2Rad(lon2);
var R = 6371; // km
var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
var y = (lat2 - lat1);
var d = Math.sqrt(x * x + y * y) * R;
return d;
}
var lat = 20; // user's latitude
var lon = 40; // user's longitude
var cities = [
["city1", 10, 50, "blah"],
["city2", 40, 60, "blah"],
["city3", 25, 10, "blah"],
["city4", 5, 80, "blah"]
];
function NearestCity(latitude, longitude) {
var minDif = 99999;
var closest;
for (index = 0; index < cities.length; ++index) {
var dif = PythagorasEquirectangular(latitude, longitude, cities[index][1], cities[index][2]);
if (dif < minDif) {
closest = index;
minDif = dif;
}
}
// echo the nearest city
alert(cities[closest]);
}
With HTML5, you can pull the location of the user and then compares this example using a Haversine function (function below taken from here):
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)
}
You can calculate the distance by latitude with your location and the cities locations. And find the shortest and draw. To calculate you can read more in http://www.movable-type.co.uk/scripts/latlong.html

How to find the angle between two locations defined by latitude or longitude using javascript? [duplicate]

I want to calculate the bearing from point 1 to point 2
The input format is 52.070564 - 4.407116
No matter what i try i cannot get an correct output.
The formula i use is :
// koers berekenen
var y = Math.sin(ln-ln1) * Math.cos(lt);
var x = Math.cos(lt1)*Math.sin(lt) -
Math.sin(lt1)*Math.cos(lt)*Math.cos(ln-ln1);
var radians = Math.atan2(y, x);
var bearing = Math.round(radians * (180/Math.PI));
/* >>>>>> original <<<<<<<
var y = Math.sin(λ2-λ1) * Math.cos(φ2);
var x = Math.cos(φ1)*Math.sin(φ2) -
Math.sin(φ1)*Math.cos(φ2)*Math.cos(λ2-λ1);
var brng = Math.atan2(y, x).toDegrees();
φ1,λ1 is the start point, φ2,λ2 the end point (Δλ is the difference in longitude)
*/
You can calculate bearing using this functions:
// Converts from degrees to radians.
function toRadians(degrees) {
return degrees * Math.PI / 180;
};
// Converts from radians to degrees.
function toDegrees(radians) {
return radians * 180 / Math.PI;
}
function bearing(startLat, startLng, destLat, destLng){
startLat = toRadians(startLat);
startLng = toRadians(startLng);
destLat = toRadians(destLat);
destLng = toRadians(destLng);
y = Math.sin(destLng - startLng) * Math.cos(destLat);
x = Math.cos(startLat) * Math.sin(destLat) -
Math.sin(startLat) * Math.cos(destLat) * Math.cos(destLng - startLng);
brng = Math.atan2(y, x);
brng = toDegrees(brng);
return (brng + 360) % 360;
}
start_latitude = 12.9389352
start_longitude = 77.6994306
stop_latitude = 12.939103
stop_longitude = 77.705825
var y = Math.sin(stop_longitude-start_longitude) * Math.cos(stop_latitude);
var x = Math.cos(start_latitude)*Math.sin(stop_latitude) -
Math.sin(start_latitude)*Math.cos(stop_latitude)*Math.cos(stop_longitude-start_longitude);
var brng = Math.atan2(y, x) * 180 / Math.PI;
alert("Bearing in degreee: " + brng);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources