Is there a way of converting a Latitude and Longitude value into a place name and then being able to display that name on a HTML page?
if ('geolocation' in navigator) {
let watchID = navigator.geolocation.watchPosition(position => {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
console.log(latitude, longitude);
}, error => {
console.log(error.code);
}, {
enableHighAccuracy: true
});
console.log(watchID);
} else {
console.log("Not Supported");
}
The code can return the latitude and longitude and they can be displayed, I want to get the specific place if possible and display it on the page or record it in a table?
Basically, you need three things:
A list of places with their coordinates. That's sort of out of scope for this site.
A distance function. You can either use the cosine rule or haversine rule for that.
A nearest neighbour algorithm that's better than O(n). For that, you can e.g. partition your set from 1, google "sphere triangular tesselation" for that, and then you can optimize your nearest neighbour algorithm.
Related
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.
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/
I am working on something to blacklist unwanted locations with the location service. Here is my current code:
How can I implement a blacklist feature?
if (navigator.geolocation) {
// Locate position
navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
alert('Your device location is not approved.');
}
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
var thediv = document.getElementById('locationinfo');
alert('Your HWID is compliant of ProtoProt regulations.');
}
function errorFunction(pos) {
alert('Error: (PROTOPROT_POS_DENIED). We only use your HWID for checking compliance. Enable location to enter.');
}
Maintain a list of locations given by two points w,y.
Each w,y represent the two opposite points of a w,x,y,z square which represents the blacklisted location.
Each point has longitude and latitude coordinates, so w = [long, lat] and y = [long, lat]
With those, you can rebuild all the [long, lat] of all the w,x,y,z corners of your square, thus representing the blacklisted area.
Now, it's rather easy to know the boundaries of forbidden location: any point [long, lat] which is within the square is blacklisted.
You can store those values within a Javascript Object (a dictionary) which can be stored in a distinct ".js" file. JSON representation could look like:
blacklisted_areas = {
'area 51' : [w, y], // Replace w y with the floats of long and lat
'pink unicorn zoo' : [w, y], // same
// etc.
};
Access:
long = blacklisted_area['area 51'][0]
I have the following data.
1.source name.
2.destination name.
I need to find lat-long pairs on the path from source to destination.Is there any google Api available for it??. I refered this questions Finding intermediate Lattitude Longitude between two given points but can't understand the whole thing.Can any one have simpler answer for this ?
EDIT
here is what i am tried
//store lat and long
var sd_array=[];
$('#processbtn').click(function(e){
//get source and destination name
var source=$('#source').val();
var destination=$('#destination').val();
if(source==''||destination==''){
alert("all fields required");
}else{
//decode lat-long from address
getLatitudeAndLongitude(source);
getLatitudeAndLongitude(destination);
}
});
function getLatitudeAndLongitude(address){
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
//store to array
sd_array.push(latitude);
sd_array.push(longitude);
}
});
}
function getInterMediateLatLong(sd_array){
//get intermediate locations
/*sd_array[0] source lat
sd_array[1] source long
sd_array[2] destination lat
sd_array[3] destination long*/
}
i need the help to achieve get intermediate locations.
You must understand first that it is a Mathematical problem, but is simple. Google will return a set o XY points... The procedure is:
Express correctly the "reference points" S and D, the Source and the Destination points. So Sx,Sy,Dx,Dy. They are not "names", are XY coodenates (!).
Check how to say to Google-API how many points you need
submit your query to Google-API: Edit your question to show your query (Javascript code) to us! them we can discuss here.
You need to express
{path[]: LatLngPathes, samples: 4}
Javascript fragment example to obtain LatLngPathes:
var source = new google.maps.LatLng(36.578581, -118.291994);
var destination = new google.maps.LatLng(36.606111, -118.062778);
Since the type underlying each of lat and lon is real (AKA double or float) simply add the source and end-point variables and divide each result by 2.0 .
var mid_lat = (lat_source + lat_dest ) / 2.0 ;
var mid_lon = (lon_source + lon_dest ) / 2.0 ;
Then the coordinates of the mid-point are mid_lat, mid_lon .
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°?