If I have stored in my DB several latlng points, and I want to compare those points with my actual latlng position( giving me the distance between each latlng points with my actual latlng), how would that be posible with google maps API? or it's something that it would be easier using my database?
Computing the distance between two points on a sphere requires the use of the haversine formula, which requires a pretty solid understanding of trigonometry.
The easier way would be to leverage the Google Maps API which has the handy function computeDistanceBetween in the google.maps.geometry.spherical namespace.
Here's some sample code for using computeDistanceBetween:
var home = ['London', new google.maps.LatLng(51.5, -0.1167)];
var pts = [
['Prague', new google.maps.LatLng(50.08, 14.43)],
['Paris', new google.maps.LatLng(48.856614, 2.3522219000000177)],
['Berlin', new google.maps.LatLng(52.5200065999, 13.404953999999975)]
];
// provide a shortcut for the distance function
var dist = google.maps.geometry.spherical.computeDistanceBetween;
pts.forEach(function(pt){
var d = dist(home[1], pt[1])/1000;
// d is now the distance (in km) between the home coordinate and the point
});
See working example here: http://jsfiddle.net/aJTK2/5/
If you intend to use your database for this sort of work, you might want to think about using PostGIS for this. With PostGIS installed:
CREATE EXTENSION postgis;
SELECT ST_Distance(
ST_GeographyFromText('POINT(115.764286 -31.746416)'),
ST_GeographyFromText('POINT(151.036606 -33.906896)')
);
Produces:
st_distance
------------------
3295294.42439749
(1 row)
Compared to Google Maps output, which thinks it's about 3700 km (walking, not crow-flies).
So that seems about right, distance wise.
Note that this is spheroid distance, i.e over the earth's surface, not point-to-point through it.
Watch out for the co-ordinate order in PostGIS vs Google Maps.
To learn more about PostGIS:
Introduction to PostGIS
Introduction to PostGIS - Geography
PostGIS.net
Related
I am learning how to use the Mapbox API for my node app and I want to perform calculations on the backend like getting the distance between two coordinates.
How can I achieve this?, the Mapbox documentation doesn't make this clear...
Set-up the SDK
const mapboxSdk = require("mapbox")
let mapbox = new mapboxSdk(process.env.MAPBOX_TOKEN)
// EXAMPLE OF WHAT I WANT TO DO
coordA = {lat : 33.968123, long: -118.419454}
coordB = {{lat : 33.997223, long: -117.929145}}
const distance = await mapbox.getDistance(coordA, coordB)
console.log(distance)
I believe Mapbox recommends using the Turf.js library for this type of thing: Turf.js Distance Function. However, the distance between two lat/long coords is a simple geometry problem that doesn't need any external APIs/libraries, and can be calculated from your coordinates using the Haversine Formula. Check this SO question for implementations of the Haversine formula as a javascript function.
I'm having a problem
I would like to ask what the most efficient way is to check if latitude and longitude coordinates are inside a range (for example 100 meters) from a list of latitudes and longitude points.
For example I have this list of coordinates:
[[48.34483,51.16.24517],[48.484,16.2585],[48.361,51.87739419],[6.38477205,51.87745015],[48.3645,51.16.73167],[6.38391099,51.87755068],[48.3575,16.725],[6.38380232,51.87720004],[6.38376297,51.87708017],[6.38375183,51.87704018],[6.38373055,51.8769829]]
I would like somehow that all points that are in a specific range (100m for example),
to be somehow grouped.
Is there any way how I can indicate that for example from the above list:
[48.484,16.2585],[48.361,51.87739419] and [48.3575,16.725]
are in a radius of 100m ( distance between these points is less then 100m) and they should be groped
Sounds like a great question for a GIS professional; you could perhaps post on gis.stackexchange.com. Are you using a mapping technology where you already have access to an API? The functionality that you're looking for are referred to as geometric operations. I'd start by looking into geometry functions available in an API which calculate the distance between points. You could find the geometric center of all of the points, then request the geometry API to create a buffer around that point. Next, query if each point falls within that buffer.
Found a post which might help with finding the center of the points here:
How do I find the center of a number of geographic points?
Also found a post on stackexchange which sounds very similar to yours, only the post is in reference to ArcGIS and the Point Distance (Analysis) tool:
https://gis.stackexchange.com/q/91571/81346
Ideally you'd use a geospatial db for this, to avoid performance issues when dealing with increasing numbers of points. MySQL, Postgres etc all support geospatial functions.
But as you've tagged your question with javascript, I'll post a JS solution. There's an npm package called haversine - with it, you should be able to loop through each point and return the other points that are within 100m. Something like:
// bring in haversine from npm
var haversine = require("haversine");
// define the full list of points
var data = [
[48.34483,51.1624517],
[48.484,16.2585],
[48.361,51.87739419],
[6.38477205,51.87745015],
[48.3645,51.1673167],
[6.38391099,51.87755068],
[48.3575,16.725],
[6.38380232,51.87720004],
[6.38376297,51.87708017],
[6.38375183,51.87704018],
[6.38373055,51.8769829]
];
var points = data.map(point => new Object({latitude: point[0], longitude: point[1]}));
// var to store results in
var results = [];
// loop through the points
points.forEach((pair) => {
var nearby = points;
// filter the full list to those within 100m of pair
nearby.filter(point => haversine(pair, point, {unit: 'mile'}) <= 100);
results.push({
'point': pair,
'nearby': nearby
});
});
console.log(results);
Note: I corrected some of the points in your list, which had double decimals so weren't valid
I am new to use this API.
Basically I am developing a widget that calculate freight between two places, so i just need to compute distance only there is no need of showing Map.
If any one has simple explanation please share with me.
I have gone through this link but not able to identify which part of code i need to use for finding distance only.
you can use Geometry computeDistanceBetween()
var placeA = new google.maps.LatLng(-33.873, 151.13);
var placeB = new google.maps.LatLng(-33.92, 151.05);
console.log(google.maps.geometry.spherical.computeDistanceBetween(placeA, placeB));
Reference: https://developers.google.com/maps/documentation/javascript/geometry#SphericalGeometry
I am having a hard time trying to figure out how to wrap a Lat/Lng point with a rectangle that is 20meters by 20meters.
Use-case:
> Click on a marker on the Google map
< Infowindow opens
> Click a button called 'Wrap' on the Infowindow
< Automatically create a 20x20m box with the marker dead center
I have no issue creating the rectangle (square rather) on the map I just need to know how to compute the border of the square in Lat/Lng.
On a normal grid I would get the NW and SE points by:
marker_nw_y = marker_y + 10 (meters)
marker_nw_x = marker_x - 10
marker_se_y = marker_y - 10
marker_se_x = marker_x + 10
From there I could create the graphic square etc.. But with Lat/Lng it gets more complicated because changing the degree between two points is different depending on where you are.
How could I do this? Manipulating the Haversine formula? Instead of solving for 'distance' I would need to rearrange and solve for one of the coordinates, but rearranging that formula is difficult and im not sure whether my results are even right.
I believe this question includes code that should let you accomplish what you're looking for.
I would use Mike Williams' eshapes library which I ported to the Google Maps API v3 to make squares with a "radius" of 20*sqrt(2)/2 meters.
example using my port of Mike Williams' eshapes library
The click listener would be:
google.maps.event.addListener(map, "click", function(evt) {
var marker = new google.maps.Marker({ position: evt.latLng, map: map});
var square = google.maps.Polyline.RegularPoly(evt.latLng,20*Math.sqrt(2)/2,4,0,"#ff0000",1,1);
square.setMap(map);
});
working example
Simpler working example based off alternate answer in link from Kelvin Mackay
I have a latitude/longitude value and distance value. I need to calculate a bounding box with the given location as the center. so if the distance was 200 meters then the rectangle box should be 200 meters in front, behind, to left and right.
How do I go about doing this using JavaScript?
You need to translate your coordinate lat/long to a x/y-value in the map projection you are using, then you can calculate your bounding box.
I don't know the Google Maps API well, and I don't know exactly what you want to do with your box. But maybe GBounds, GMercatorProjection and GLatLngBounds can be helpful. And if Google Maps API doesn't support calculations for the map projection you are using, then it can be helpful to use Proj4js. And maybe you want to read up about Map projections. Google Maps is by default using Mercator projection.
Here are a number of useful javascript functions for working with latitude and longitude:
http://www.movable-type.co.uk/scripts/latlong.html
For bounding box around a point, a simple modification using the above javascript library might be:
LatLon.prototype.boundingBox = function (distance)
{
return [
this.destinationPoint(-90, distance)._lon,
this.destinationPoint(180, distance)._lat,
this.destinationPoint(90, distance)._lon,
this.destinationPoint(0, distance)._lat,
];
}
(This uses the "Destination point given distance and bearing from start point" calculation.)
If you're using the V3 API, you can make use of Rectangle and Circle. See this blogger's brief description and examples:
http://apitricks.blogspot.com/2010/02/rectangle-and-circle-of-v3.html