How to Calculate the Latlng of a Point a Certain Distance Away from Another

How to calculate the latlng of a point a certain distance away from another?

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:

Google Maps Geometry

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):

Close to north pole

How to calculate the lat/lng of a point a certain distance away from another using Nodejs or javascript

Referring to the below geometry diagram, the only co-ordinate you need to calculate is - (x2, y2) and rest of the two co-ordinate you can calculate using current long, lat - (x1, y1) and computed - (x2, y2)

Sample Image

So basically you need a function which will take current lat, long i.e. - (x1, y1), a distance which is √2 * 10km in your example and bearing angle to point (x2, y2) which at 135 degrees.

let llFromDistance = function(latitude, longitude, distance, bearing) {  // taken from: https://stackoverflow.com/a/46410871/13549   // distance in KM, bearing in degrees
const R = 6378.1; // Radius of the Earth const brng = bearing * Math.PI / 180; // Convert bearing to radian let lat = latitude * Math.PI / 180; // Current coords to radians let lon = longitude * Math.PI / 180;
// Do the math magic lat = Math.asin(Math.sin(lat) * Math.cos(distance / R) + Math.cos(lat) * Math.sin(distance / R) * Math.cos(brng)); lon += Math.atan2(Math.sin(brng) * Math.sin(distance / R) * Math.cos(lat), Math.cos(distance / R) - Math.sin(lat) * Math.sin(lat));
// Coords back to degrees and return return [(lat * 180 / Math.PI), (lon * 180 / Math.PI)];
}
console.log(llFromDistance(19.0659115, 72.8574557, Math.sqrt(2)*10, 135))

How to calculate the lat/lng of a point a certain distance from another point?

All you need to do is take the original point and compute the distance for one degree to the east or west. That will give you the distance per degree along that line of latitude. Then divide r by the distance per degree and it will tell you how many degrees B is to the east or west.

Get lat/long given current point, distance and bearing

Needed to convert answers from radians back to degrees. Working code below:

import math

R = 6378.1 #Radius of the Earth
brng = 1.57 #Bearing is 90 degrees converted to radians.
d = 15 #Distance in km

#lat2 52.20444 - the lat result I'm hoping for
#lon2 0.36056 - the long result I'm hoping for.

lat1 = math.radians(52.20472) #Current lat point converted to radians
lon1 = math.radians(0.14056) #Current long point converted to radians

lat2 = math.asin( math.sin(lat1)*math.cos(d/R) +
math.cos(lat1)*math.sin(d/R)*math.cos(brng))

lon2 = lon1 + math.atan2(math.sin(brng)*math.sin(d/R)*math.cos(lat1),
math.cos(d/R)-math.sin(lat1)*math.sin(lat2))

lat2 = math.degrees(lat2)
lon2 = math.degrees(lon2)

print(lat2)
print(lon2)

Calculate distance between two latitude-longitude points? (Haversine formula)

This link might be helpful to you, as it details the use of the Haversine formula to calculate the distance.

Excerpt:

This script [in Javascript] calculates great-circle distances between the two points –
that is, the shortest distance over the earth’s surface – using the
‘Haversine’ formula.

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)
}

How to calculate the lat/lng of a 2nd point given 1st point and distance?

You need one more parameter, namely "bearing". Then:

var d = radius/6378800; // 6378800 is Earth radius in meters
var lat1 = (PI/180)* centerLat;
var lng1 = (PI/180)* centerLng;

// Go around a circle from 0 to 360 degrees, every 10 degrees or set a to your desired bearing, in degrees.
for (var a = 0 ; a < 361 ; a+=10 ) {
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 ;
var lat = y*(180/PI);
var lon = x*(180/PI);

// Convert the lat and lon to pixel, if needed. (x,y)
}

Originally from this other SO thread:
How to change 1 meter to pixel distance?

Calculate lat/long coords a specific distance away from another pair of lat/long coords

The set of points a fixed distance from a central point has infinite members, so it's not possible to list out every one. However, given a single point you could check if it is within the set by using the distanceFromLocation: method.

Mathematically, given a radius coordinate (long, lat) and assuming the Earth is flat, the equation of the circle with radius (distance) r would be

r^2 = (x - long)^2 + (y - lat)^2

With the use of some magic, this becomes

x = r cosθ - long; y = r sinθ - lat

So now you can punch in any arbitrary angle and for a known distance/radius get a point on the edge of the circle. In map terms, the angle 0 will give you the point on the circle straight east of the center. Positive angles go counterclockwise around the center.

In code:

-(CLLocation*)locationForAngle:(float)angle fromCenterLocation:(CLLocation *)center withDistance:(float)distance {
//angle must be in radians
float longitude = distance * cosf(angle) - center.coordinate.longitude;
float latitude = distance * sinf(angle) - center.coordinate.latitude;
return [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
}

Edit: I accidentally dropped a few terms

Find coordinate a certain distance and heading away from another coordinate

Use computeOffset. From the documentation:

computeOffset(from:LatLng, distance:number, heading:number, radius?:number)

Return Value: LatLng

Returns the LatLng resulting from moving a distance from an origin in the specified heading (expressed in degrees clockwise from north).

var distance = google.maps.geometry.spherical.computeDistanceBetween(coord1, coord2);
var heading = google.maps.geometry.spherical.computeHeading(coord1, coord2);
var newPt = google.maps.geometry.spherical.computeOffset(coord1, distance/2, heading);

code snippet:

function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var coord1 = new google.maps.LatLng(37.399228, -122.208676); // SouthWest corner
var coord2 = new google.maps.LatLng(37.484548, -122.075124); // NorthEast corner
var distance = google.maps.geometry.spherical.computeDistanceBetween(coord1, coord2);
var heading = google.maps.geometry.spherical.computeHeading(coord1, coord2);
var newPt = google.maps.geometry.spherical.computeOffset(coord1, distance / 2, heading);
console.log(newPt.toUrlValue(6) + ", distance=" + distance.toFixed(2) + ", heading=" + heading);
var marker = new google.maps.Marker({
position: newPt,
map: map
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map_canvas"></div>

Calculating new longitude, latitude from old + n meters

The number of kilometers per degree of longitude is approximately

(pi/180) * r_earth * cos(theta*pi/180)

where theta is the latitude in degrees and r_earth is approximately 6378 km.

The number of kilometers per degree of latitude is approximately the same at all locations, approx

(pi/180) * r_earth = 111 km / degree 

So you can do:

new_latitude  = latitude  + (dy / r_earth) * (180 / pi);
new_longitude = longitude + (dx / r_earth) * (180 / pi) / cos(latitude * pi/180);

As long as dx and dy are small compared to the radius of the earth and you don't get too close to the poles.

How can I quickly estimate the distance between two (latitude, longitude) points?

The answers to Haversine Formula in Python (Bearing and Distance between two GPS points) provide Python implementations that answer your question.

Using the implementation below I performed 100,000 iterations in less than 1 second on an older laptop. I think for your purposes this should be sufficient. However, you should profile anything before you optimize for performance.

from math import radians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
# Radius of earth in kilometers is 6371
km = 6371* c
return km

To underestimate haversine(lat1, long1, lat2, long2) * 0.90 or whatever factor you want. I don't see how introducing error to your underestimation is useful.



Related Topics



Leave a reply



Submit