Efficient way to find bounding values in an array of tuples? - javascript

I have an array of latitude/longitude values, rather like this:
var points = ["-0.15868039429188,51.534183502197", "-0.158839,51.534916", "-0.158814,51.53503", "-0.158817,51.535076", "-0.157492,51.535404", "-0.155767,51.535816", "-0.155696,51.535831", "-0.15526,51.535934", "-0.153192,51.536388", "-0.152282,51.536575", "-0.152467,51.536968", "-0.152592,51.53727", "-0.152682,51.53756", "-0.152074,51.53754", "-0.151921,51.537464", "-0.151732,51.538368", "-0.151373,51.538841", "-0.150622,51.539482", "-0.150237,51.539761", "-0.150047,51.539875", "-0.149957,51.539921", "-0.149594,51.540108", "-0.149563,51.540134", "-0.149536,51.540161", "-0.149497,51.540184", "-0.149445,51.540203"];
(OK, it's not strictly an array of tuples, but close enough.)
I want to find the four bounds of the array - i.e. the latitude and longitude north/west/south/east bounds.
Currently I'm doing this:
$.each(coords, function(index, value) {
var j = value.split(',');
var coord_lat = parseFloat(j[1]);
var coord_lng = parseFloat(j[0]);
if (coord_lat>nbound) {
nbound = coord_lat;
} else if (coord_lat<sbound) {
sbound = coord_lat;
}
if (coord_lng<ebound) {
ebound = coord_lng;
} else if (coord_lng>wbound) {
wbound = coord_lng;
}
});
However, this doesn't feel very efficient. Can anyone recommend a better way to do it?

If you aren't constrained to the current input format you could use objects instead. This will avoid the expensive split and parseFloat calls.
var points = [
{ latitude: -0.15868039429188, longitude: 51.534183502197 },
{ latitude: -0.158839, longitude: 51.534916 },
{ latitude: -0.155696, longitude: 51.535831 }
];

This is very small, but there is some unnecessary overhead in using jquery's each method. You're slightly better off here using a plain for loop on the array of points.

I think your longitude tests are back-to-front:
if (coord_lng < ebound) {
ebound = coord_lng;
Longitude increases eastward, so the < should be >.
In a system where longitude is expressed as +ve for east and -ve for west, just east of 180° is -179° and just west is +179°. Should ebound be +179 and wbound be -179 with an interval of 358°, or the other way around with an interval of 2°?

Related

How to find nearest latitude/longitude from big json array of lat/lng

I'm building a website that locates your device and shows you 4 of the nearest parking meters.
For the parking meters I'm using an API to retrieve the latitude and longitude and using Google Directions API to set the start and destination coordinates and generate a route. All the parking meters are in a radius of ~2,5 km.
Now to find the 4 nearest parking meters I was thinking of running a formula and going through each record of the API to find the nearest 4. But (I think) that would take too much processing time to load into a website, therefore making it slow. There are nearly 1200 records in the API.
To calculate the route via lat/lng coordinates I'm using the following code:
fetch('https://data.stad.gent/api/records/1.0/search/?dataset=locaties-parkeerautomaten-gent&q=&rows=\
1200&facet=parkeertariefzone&facet=bewonerszone&facet=betaalmodus&facet=status&facet=categorie')
.then(response => response.json())
.then(json => {
let start = new google.maps.LatLng(51.053788, 3.730767);
let end1 = new google.maps.LatLng(json.records[0].geometry.coordinates[1], json.records[0].geometry.coordinates[0]);
let request = {
origin: start,
destination: end1,
travelMode: 'WALKING'
};
let display = new google.maps.DirectionsRenderer();
let services = new google.maps.DirectionsService();
services.route(request, function (result, status) {
if (status == 'OK') {
display.setDirections(result);
}
})
let map1 = new google.maps.Map(document.getElementById("map1"));
display.setMap(map1);
});
QUESTION: What is in your opinion the best way to calculate and return the 4 nearest lat/lng points in an API with nearly 1200 records with a ~2,5 km radius using JavaScript?
I'm not really sure how to tackle this challenge on, any answer would be appreciated.
NOTE: It is my first question/post so if I missed something or did something stupid, do let me know, thanks in advance :)
In case anyone comes here looking for a solution, how I solved it is by the following code:
for (let i = 0; i < json.length; i++) {
if ((Math.abs(json[i].coordinates[1] - start.lat)) + ((Math.abs(json.[i].coordinates[0] - start.lng))) < sumLatLng) {
closest = json[i];
sumLatLng = (Math.abs(json.[i].coordinates[1] - start.lat)) + ((Math.abs(json.[i].coordinates[0] - start.lng)))
} else {
console.log("error");
}
}
Basically what I do is take the sum of the starting lat & lng, subtract the lat & lng of each record from the API and take the absolute of the result. If the result is smaller than the previous result, that means that its closer.

Get latitude and longitude stops in a trimble map

Using trimble maps, i'm creating a route with origin and destination points given by latitude and longitude. The user can put new stops at the interactive map. The problem is that when the library returns me the stops locations, it is giving me those like X and Y and not like longitude and latitude.
For example, if the origin is
Latitude: 37.66427
Longitude: -97.72388
The application is returning me the point like
x: -10878572.558428662
y: 4532106.384744367
I'm doing this to get the stops:
var routeElements = routingLayer.getRouteElements("MyRoute");
var numberOfStops = routeElements.stops.length;
for (var i = 0; i < numberOfStops; i++) {
console.log("Stop " + i);
console.log("Lon: " + routeElements.stops[i].geometry.x);
console.log("Lat: " + routeElements.stops[i].geometry.y);
}
As says at the following documentation:
https://developer.trimblemaps.com/trimble-maps/1.2/docs/routing/
I need to know the way to convert X and Y to Longitude and Latitude or get directly the LonLat with any specific command.
You'd have to use the transform function to change the point back to a geographic projection.
In this case you would need to call
routeElements.stops[i].transform(map.getProjectionObject(),new ALKMaps.Projection("EPSG:4326"))
to get a Point object where the x and y are longitude and latitude values.
It's basically the reverse of what's described here: https://developer.trimblemaps.com/trimble-maps/1.2/docs/getting-started/spherical-mercator/

Sort array based on geolocation

I want to sort array/object of cities based on my location from nearest (to my location) to furthest
I have list of locations that i get from database
How would i solve this using javascript and HTML5 geolocation?
I have something like this:
example :
var locations= [{"name":"location1" "latitude" :"31.413165123"
"longitude":"40.34215241"},{"name":"location2" "latitude" :"31.413775453"
"longitude":"40.34675341"}]
and I want to sort those location by nearest to my location
FIRST: The provided array is broken (i added commas between fields).
var locations = [{
"name": "location1",
"latitude": "31.413165123",
"longitude": "40.34215241"
}, {
"name": "location2",
"latitude": "31.413775453",
"longitude": "40.34675341"
}];
You'll need to leverage a custom sort function, which needs to return 1, -1, or 0 based on comparing 2 items.
var myLong = 42.0; // whatever your location is
var myLat = 3.16; // whatever your location is
locations.sort( function (a, b) {
// This is untested example logic to
// help point you in the right direction.
var diffA = (Number(a.latitude) - myLat) + (Number(a.longitude) - myLong);
var diffB = (Number(b.latitude) - myLat) + (Number(b.longitude) - myLong);
if(diffA > diffB){
return 1;
} else if(diffA < diffB){
return -1;
} else {
return 0; // same
}
} );
Store your location, create a function that calculates the distance between two points and then use the sort method:
function dist({latitude: lat1, longitude: long1}, {latitude: lat2, longitude: long2}) {
// I'm not very good at geography so I don't know how to calculate exactly the distance given latitudes and longitudes.
// I hope you can figure it out
// the function must return a number representing the distance
}
navigator.geolocation.getCurrentPosition(({coords}) => {
coords.latitude = parseFloat(coords.latitude)
corrds.longitude = parseFloat(coords.longitude)
locations.sort((p1, p2) => dist(coords, {latitude: parseFloat(p1.latitude), longitude: parseFloat (p1.longitude)}) -
dist(coords, {latitude: parseFloat(p2.latitude), longitude: parseFloat(p2.longitude)}))
})
Hope it helps you

How to check if points are within radius with leaflet/javascript?

I have a list with 50 items:
var mylocations = [{'id':'A', 'loc':[-21,2]},...,];
How can I in leaflet or JavaScript most efficiently make it such that if I accept an input of a specific location [<longitude>,<latitude>], a radius (e.g. 50 miles)... I can get all of the "mylocations" that fall within that circle?
Using external libraries is fine.
Leaflet's L.LatLng objects include a distanceTo method:
Returns the distance (in meters) to the given LatLng calculated using the Haversine formula.
http://leafletjs.com/reference.html#latlng-distanceto
var inRange = [], latlng_a = new L.LatLng(0, 0), latlng_b;
locations.forEach(function (location) {
latlng_b_ = new L.LatLng(location.pos[0], location.pos[1]);
if (latlng_a.distanceTo(latlng_b) < 80.4672) {
inRange.push(location);
}
});

How to display markers (huge numbers) on a map which has been logically divided into segments?

What i have done so far:
i'm developing an application where i have to display more than(50K) points/Markers on the Navteq map divided into different segments.
for example: if i have 50K points i will divide all points into different segments.
if i divide 50K points into 50 segments each segment would have 1000 points (may not be 50 segments , it may depend).
right now it is working but it takes long time and hangs to render all the points on the MAP.so that i would like to perform segmentation displaying to display only few points with clustering.
so that i can get an idea of how the segment will look like.
but the problem here is i should only perform the clustering based on the segments.otherwise points from different segments willbe mixed together and displayed
as single unit and that conveys the wrong information to the user.
so here my question is: is it possible to perform the clustering based on the segment. so that only points from same segment will be clustered.
Note: if this is not possible, i would like to use Latest version of here-maps 2.5.3 (Asynchronous) may reduce some time while loading, so that i would like to use indexing functionality also while rendering the points
to improve the rendering time using nokia.maps.clustering.Index class.
i studied that indexing would reduce the time while rendering the points/markers on map. does it help in my case? could anybody please suggest how to perform indexing ?
This is the code with which i'm displaying points on map:
function displayAllLightPoints(arrLightPointCoordinats, totalLightPoints,
selectedSegmentId, totalSegmentsCount,segmentColorcode)
{
var MyTheme1 = function () {
};
segmentColorcode = segmentColorcode.substring(2,segmentColorcode.length-1);
MyTheme1.prototype.getNoisePresentation = function (dataPoint) {
var markerLightPoint = new nokia.maps.map.Marker(dataPoint, {
icon: new nokia.maps.gfx.BitmapImage("..//Images//Lightpoint//" +
segmentColorcode + ".png"),
anchor: {
x: 12,
y: 12
}
});
return markerLightPoint;
};
MyTheme1.prototype.getClusterPresentation = function (data) {
var markerLightPoint = new
nokia.maps.map.StandardMarker(data.getBounds().getCenter(), {
icon: new nokia.maps.gfx.BitmapImage("..//Images//
Segment/" + segmentColorcode + ".png", null, 66, 65),
text: data.getSize(),
zIndex: 2,
anchor: {
x: 12,
y: 12
}
});
return markerLightPoint;
};
var ClusterProvider = nokia.maps.clustering.ClusterProvider,
theme = new MyTheme1(),
clusterProvider = new ClusterProvider(map, {
eps: 0.00000000001,
minPts: 1000000,
strategy: nokia.maps.clustering.ClusterProvider.
STRATEGY_DENSITY_BASED,
theme: theme,
dataPoints: []
});
var lightpointsDataSet1 = new Array();
for (var i = 0; i < totalLightPoints; i++) {
lightpointsDataSet1[i] = { latitude: arrLightPointCoordinats[i][0],
longitude: arrLightPointCoordinats[i][1], title:
'LightPoint ' + (i + 1) };
}
clusterProvider.addAll(lightpointsDataSet1);
clusterProvider.cluster();
}
To deal with a very large (50K+) data set , I would do all the heavy number crunching server side and send over a new JSON response whenever the map is updated. Something like the HTML page described here
The key section of the code is the ZoomObserver:
var zoomObserver = function (obj, key, newValue, oldValue) {
zoom = newValue;
if (zoom < 7)
{ zoom = 7;}
if (zoom > 16)
{ zoom = 16;}
// Define the XML filename to read that contains the marker data
placeMarkersOnMaps('http://api.maps.nokia.com/downloads/java-me/cluster/'+ zoom + '.xml'
+ '?lat1=' + map.getViewBounds().topLeft.latitude
+ '&lng1='+ map.getViewBounds().topLeft.longitude
+ '&lat2='+ map.getViewBounds().bottomRight.latitude
+ '&lng2='+ map.getViewBounds().bottomRight.longitude);
};
map.addObserver("zoomLevel", zoomObserver );
Where the REST service returns a "well-known" data format which can be used to add markers and clusters to the map.
Now assuming you have two massive data sets you could make two requests to different endpoints, or somehow distinguish which cluster of data belongs to which so that you would just be returning information of the form:
{latitude':51.761,'longitude':14.33128,'value':102091},
i.e. using the DataPoint standard (which means you could use a heat map as well.
Of course, what I'm not showing here is the back-end functionality to cluster in the first place - but this leaves the client (and the API) to do what it does best displaying data, not number crunching.

Categories