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.
Related
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
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
I am trying to learn how to use the Javascript library leaflet along with d3 to create various map visualisations.
I have been following this tutorial which creates a choropleth map of the United States with some interactivity. This provides some of what I need, but the main functionality I want is to have a list of lat/long coordinates classified according to which region they belong to.
This would mean, in the tutorial map for example, if I had a lat long value (55, -3) which fell within the state of Arizona's polygon, the program could classify this point as belonging to Arizona.
Is there a function in the leaflet (or d3) library which will allow me to enter a lat long coordinate as a parameter and return the name of the feature it belongs to? The tutorial above allows you to attach a function to every feature via the onEveryFeature property and can fire mouseover events when each feature is hovered over. Surely there is a way to extend this functionality to numerically entered data instead of mouse points?
Leaflet would need some tweaking if you wish to do this. It leaves the handling of mouseclicks to the browser and therefore does not need logic for determining if a point lies inside a polygon.
I am not very knowledgeable about d3 but it's not glaringly obvious to me how it'd do this out of the box. Looking at the polygon code, I do find a clipping algorithm and intersection of infinite lines.
If you add a third library, however, this should be rather simple.
The OpenLayers Geometry library can determine if a point lies inside a polygon.
EDIT: I got this to work, see also http://jsfiddle.net/VaY3E/4/
var parser = new OpenLayers.Format.GeoJSON();
var vectors = parser.read(statesData);
var lat = 36;
var lon = -96;
var point = new OpenLayers.Geometry.Point(lon, lat);
for( var i = 0; i< vectors.length; i++ ){
if(vectors[i].geometry.intersects(point)){
alert(vectors[i].attributes['name']);
}
}
Or you could use https://github.com/maxogden/geojson-js-utils , a bit more specific library. It looks like it knows how to read GeoJSON and it has a method gju.pointInPolygon. I've not tested it though.
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