Finding intermediate latitude and longitude in javascript - javascript

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 .

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.

Convert Latitude and Longitude values to a place name and display it?

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.

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/

How To Add A Blacklist to Location

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]

Integrate Google Map with Markers from HTTPrequest Javascript

Hi there I am Using appcelerator, and I want to integrate a map with an array of markers I am getting from a HTTPRequest...
I am effing lost, totally lost.
This is how the map looks like:
var mapview = Titanium.Map.createView({
mapType: Titanium.Map.STANDARD_TYPE,
region: {latitude:33.74511, longitude:-84.38993,
latitudeDelta:0.01, longitudeDelta:0.01},
animate:true,
regionFit:true,
userLocation:true,
annotations:[mountainView]
});
And I have the example of 1 marker hardcoded ...
var mountainView = Titanium.Map.createAnnotation({
latitude:37.390749,
longitude:-122.081651,
title:"Appcelerator Headquarters",
subtitle:'Mountain View, CA',
pincolor:Titanium.Map.ANNOTATION_RED,
animate:true,
leftButton: '../images/appcelerator_small.png',
myid:1 // CUSTOM ATTRIBUTE THAT IS PASSED INTO EVENT OBJECTS
});
So yo create the marker and in the annotations section you add it to the map, the thing here is that I am getting the markers from this:
var url = "http://myURLwithMyParameters";
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this function is called when data is returned from the server and available for use
// this.responseText holds the raw text return of the message (used for text/JSON)
var result = this.responseText;
var xml = Ti.XML.parseString(result);
var items = xml.documentElement.getElementsByTagName("marker");
var name = xml.documentElement.getElementsByTagName("name");
var value = xml.documentElement.getElementsByTagName("address");
var data = [];
for (var i=0;i<items.length;i++) {
data.push({
name: items.item[i].getElementsByTagName("name")[0].textContent,
address: items.item[i].getElementsByTagName("address")[0].textContent
})
Does any one know how to integrate this?
I think I must build the map in the same function as the markers, but I've tried several options and haven't found ANY example of this in the web.
Any clue would be very appreciated.
Thank you in advance.
If all you have is an address, you'll need to forward geocode those addresses to get lat/long coordinates. Those coords are required to place annotations on the map. Check the docs at forwardGeocoder(). There's an example in the KitchenSink

Categories