Reputation: 12689
So I'm trying to find what range of latitude and longitude values I can use when trying to find other points on a map from an origin position based on the radius (e.g. 5km).
Current I'm using the Haversine formula from Calculate distance between two points in google maps V3 to calculate how long 1m is in both latitude and longitude.
var rad = function(x) {
return x * Math.PI / 180;
};
var getDistance = function(p1, p2) {
var R = 6378137; // Earth’s mean radius in meter
var dLat = rad(p2.lat - p1.lat);
var dLong = rad(p2.lng - p1.lng);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(p1.lat)) * Math.cos(rad(p2.lat)) *
Math.sin(dLong / 2) * Math.sin(dLong / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d; // returns the distance in meter
}
let origin = {lat: 40, lng: 40}
let p1 = {lat: 41, lng: 40}
let p2 = {lat: 40, lng: 41}
let latDist = getDistance(origin, p1)
let lngDist = getDistance(origin, p2)
console.log(latDist, lngDist);
let lat1m = 1/latDist
let lng1m = 1/lngDist
console.log(lat1m, lng1m)
From this, 1m in latitude is roughly 0.000008983152841195214
and 1m in longitude is roughly 0.000011726734698319366
. So 5km would just be 5000 multiplied by each of the points then plus/minus from the origin.
Was there a Google API to get possible ranges or is this the correct method?
Upvotes: 0
Views: 1544
Reputation: 11340
UPD.
I was wrong, you can use google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);
to calculate distance between two points. Docs. Just pass LatLng
objects.
OLD JS ANSWER.
As for your question, you don't need to use Google API at all. In addition, Google API doesn't provide simple functions, that can be calculated using geometry.
Let me make your code a little simplier. Length of an arc is simply radius * angle in radians
. So lat
distance is latDist = R * dLat
and lng
distance is lngDist = R * dLng * Math.cos(rad(origin.lat))
. If you calculate distances, smaller than thousand of kilometers, you can assume, that latitude
is constant within the area, hence you don't need to use complex formula for that.
var rad = function(x) {
return x * Math.PI / 180;
};
var R = 6378137; // Earth’s mean radius in meter
let origin = {lat: 40, lng: 40}
let latDist = R * rad(1)
let lngDist = R * rad(1) * Math.cos(rad(origin.lat))
console.log(latDist, lngDist);
let areaRadius = 1000; // in meters
let latitudeRangeDelta = areaRadius / latDist;
let longitudeRangeDelta = areaRadius / lngDist;
console.log('latitude of the area is within range [' + (origin.lat - latitudeRangeDelta) + ', ' + (origin.lat + latitudeRangeDelta) + ']')
console.log('longitude of the area is within range [' + (origin.lng - longitudeRangeDelta) + ', ' + (origin.lng + longitudeRangeDelta) + ']')
Upvotes: 2