About calculate distances between coordinates - javascript

I found this post:
Google Maps - How to get the distance between two point in metre?
I have the same problem, my variable "a" has the NaN value. I prefer not using google api if I can do it.
I am using the code in this web page: http://www.movable-type.co.uk/scripts/latlong.html
But my variables still return NaN...
This is my code:
function actualizaLimpieza(jsonData){ //jsonData keeps all points (lat&lon)
var latJSON;
var lonJSON;
var R = 6371; // km
var dLat;
var dLon;
var lat1;
var lat2;
var a;
var c;
var d;
latGPS = 43.466827534582606; //this are supossed to be gotten by gps, but for try...
lonGPS = -3.863614797592163;
for(i = 0; i < jsonData.length; i ++){
latJSON = jsonData[i].lng;
lonJSON = jsonData[i].lat;
dlat = toRad(latJSON-latGPS);
dlon = toRad(lonJSON-lonGPS);
latGPS = toRad(latGPS);
latJSON = toRad(latJSON);
a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(latGPS) * Math.cos(latJSON);
alert("a vale: " + a); //returns NaN
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
alert("c vale: " + c);
d = R * c;
alert("d vale: " + d);
if(d < 0,010){
alert("less than 10 meters");
}
}
}
function toRad(degrees){
return degrees * Math.PI / 180;
}
Should I do any more changes to get it working? Any script I should add? I haven't add anyone for this work.
Ok, I fail writing variables: dlat != dLat... Now it works more or less

Related

I am trying to get markers near user location by calculating distance using haversine formula

Hey guys can anybody help me why i am getting an error in this code
Here is the code.
getWithinDistance: function(){
var selectedMarker = [];
var lat1 = this.state.region.latitude;
var lon1 = this.state.region.longitude;
for(var i = 0 ; i <= 3 ; i++)
{
var lat2 = this.state.a[i].latitude;
var lon2 = this.state.a[i].longitude;
var R = 6371;
var dLat = (lat2-lat1) * (Math.PI/180);
var dLon = (lon2-lon1) * (Math.PI/180);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos((lat1) * (Math.PI/180)) * Math.cos((lat2) * (Math.PI/180)) * Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
if(d <= 2.00){
var latlng = {
latitude: lat2,
longitude: lon2
}
selectedMarker.push(latlng);
}
}
console.log(selectedMarker);
var at = selectedMarker.map(marker => {
return(
<MapView.Marker coordinate={marker.latlng} />
);
})
},
I am getting Warning: Failed prop type: Required prop coordinate was not specified. but when i log it i can see two markers in the array selectedMarker[]
here is the snap of log which i get
Thanks in advance.
You have placed the return statement inside your for loop. So the the loop will exit after the first iteration.
Take these lines out of the for loop.
return (
<MapView.Marker coordinate={this.state.a[i]} />
);
Edit your for loop to store all the markers that are within the required distance in an array and then after the for loop return that array
You can use Array.prototype.map() to iterate and get the values.
Like this:
(ES6 Style)
getWithinDistance: function(){
const lat1 = this.state.region.latitude;
const lon1 = this.state.region.longitude;
const R = 6371
this.state.a.map(coordinate => {
const dLat = (coordinate.latitude - lat1) * (Math.PI/180)
const dLon = (coordinate.longitude - lon1) * (Math.PI/180)
const a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos((lat1) * (Math.PI/180)) * Math.cos((lat2) * (Math.PI/180)) * Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
const d = R * c
console.log(coordinate, d)
}
}
This will show the coordinates with their distance to your location.
The return statement has to be outside the map() function. And return whatever you want to achieve.

Google map API v.3 find nearest point from one point to point on polyline

I`ve got a map with a polyline. The server will responds me with a LatLng point on a map. I need to check if the point from the server situated on a polyline edge. If not, i need to find the nearest point on the polyline and place a marker on the nearest point on the polyline. For example, if the server responds me with a point A, i need to place a marker to a point B.
I find a good library http://wtp2.appspot.com/cSnapToRouteDemo.html, but this library is for Google API ver. 2, and i'm using Google API ver. 3. Is there any alternative for Google API ver. 3 ? Thank's.
Found an easier solution.Using turf.js.Just use your polyline coordinates to create turf line and marker position for creating turf point.
then;
var line = turf.lineString(Your polyline coordinates in GeoJson array);
var pt = turf.point([Marker_Lon, Marker_Lat]);
var snapped = turf.pointOnLine(line, pt);
var pstnOnLine = { lat: snapped.geometry.coordinates[1], lng: snapped.geometry.coordinates[0] };
var distToLine = snapped.properties.dist
This way you can calculate the distance and coordinates on your polyline easily.
You can find out more from Turf website.
The Google Maps Javascript API has a Geometry library.
The Geometry library has a isLocationOnEdge function. See the documentation.
To determine whether a point falls on or near a polyline, or on or near the edge of a polygon, pass the point, the polyline/polygon, and optionally a tolerance value in degrees to google.maps.geometry.poly.isLocationOnEdge(). The function returns true if the distance between the point and the closest point on the line or edge falls within the specified tolerance. The default tolerance value is 10-9 degrees.
You must include the library this way:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">
</script>
And if you need more than one library, for example:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry,places">
</script>
Full documentation is here.
If you need to find the point on the Polyline, you can use this ported to v3 version of the library you mentioned in your question:
var mapRoute;
var rtPoints;
var centerMAP = new google.maps.LatLng(-7.402438, 110.446957);
function gLatLngFromEN(e, n) {
var ogbLL = NEtoLL(e, n);
var pc = OGBToWGS84(ogbLL.lat, ogbLL.lon, 0);
return new google.maps.LatLng(pc.lat, pc.lon);
}
function routeMap() {
mapRoute = new google.maps.Map(document.getElementById('mapRoute'), {
center: centerMAP,
zoom: 14,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
mapRoute.setCenter(gLatLngFromEN(469000, 169000), 13);
var rtPoints = new Array();
rtPoints.push(gLatLngFromEN(468000, 168000));
rtPoints.push(gLatLngFromEN(468000, 170000));
rtPoints.push(gLatLngFromEN(470000, 170000));
rtPoints.push(gLatLngFromEN(470000, 168000));
var rtPoly = new google.maps.Polyline({
path: rtPoints,
strokeColor: "#0000FF",
strokeWeight: 3,
map: mapRoute
});
var container = document.createElement("div");
container.style.fontFamily = 'Arial';
container.style.fontSize = 'XX-Small';
var ptr = document.createElement("INPUT");
ptr.style.width = "100px";
ptr.type = "Text";
ptr.readOnly = true;
ptr.id = "distPtr";
container.appendChild(ptr);
document.getElementById("control").appendChild(container);
google.maps.event.addListener(mapRoute, 'mousemove', function (point) {
document.getElementById('distPtr').value = Math.round(bdccGeoDistanceToPolyMtrs(rtPoly, point.latLng));
});
}
google.maps.event.addDomListener(window, 'load', routeMap);
// Code to find the distance in metres between a lat/lng point and a polyline of lat/lng points
// All in WGS84. Free for any use.
//
// Bill Chadwick 2007
// updated to Google Maps API v3, Lawrence Ross 2014
// Construct a bdccGeo from its latitude and longitude in degrees
function bdccGeo(lat, lon)
{
var theta = (lon * Math.PI / 180.0);
var rlat = bdccGeoGeocentricLatitude(lat * Math.PI / 180.0);
var c = Math.cos(rlat);
this.x = c * Math.cos(theta);
this.y = c * Math.sin(theta);
this.z = Math.sin(rlat);
}
bdccGeo.prototype = new bdccGeo();
// internal helper functions =========================================
// Convert from geographic to geocentric latitude (radians).
function bdccGeoGeocentricLatitude(geographicLatitude)
{
var flattening = 1.0 / 298.257223563;//WGS84
var f = (1.0 - flattening) * (1.0 - flattening);
return Math.atan((Math.tan(geographicLatitude) * f));
}
// Convert from geocentric to geographic latitude (radians)
function bdccGeoGeographicLatitude (geocentricLatitude)
{
var flattening = 1.0 / 298.257223563;//WGS84
var f = (1.0 - flattening) * (1.0 - flattening);
return Math.atan(Math.tan(geocentricLatitude) / f);
}
// Returns the two antipodal points of intersection of two great
// circles defined by the arcs geo1 to geo2 and
// geo3 to geo4. Returns a point as a Geo, use .antipode to get the other point
function bdccGeoGetIntersection( geo1, geo2, geo3, geo4)
{
var geoCross1 = geo1.crossNormalize(geo2);
var geoCross2 = geo3.crossNormalize(geo4);
return geoCross1.crossNormalize(geoCross2);
}
//from Radians to Meters
function bdccGeoRadiansToMeters(rad)
{
return rad * 6378137.0; // WGS84 Equatorial Radius in Meters
}
//from Meters to Radians
function bdccGeoMetersToRadians(m)
{
return m / 6378137.0; // WGS84 Equatorial Radius in Meters
}
// properties =================================================
bdccGeo.prototype.getLatitudeRadians = function()
{
return (bdccGeoGeographicLatitude(Math.atan2(this.z,
Math.sqrt((this.x * this.x) + (this.y * this.y)))));
}
bdccGeo.prototype.getLongitudeRadians = function()
{
return (Math.atan2(this.y, this.x));
}
bdccGeo.prototype.getLatitude = function()
{
return this.getLatitudeRadians() * 180.0 / Math.PI;
}
bdccGeo.prototype.getLongitude = function()
{
return this.getLongitudeRadians() * 180.0 / Math.PI ;
}
// Methods =================================================
//Maths
bdccGeo.prototype.dot = function( b)
{
return ((this.x * b.x) + (this.y * b.y) + (this.z * b.z));
}
//More Maths
bdccGeo.prototype.crossLength = function( b)
{
var x = (this.y * b.z) - (this.z * b.y);
var y = (this.z * b.x) - (this.x * b.z);
var z = (this.x * b.y) - (this.y * b.x);
return Math.sqrt((x * x) + (y * y) + (z * z));
}
//More Maths
bdccGeo.prototype.scale = function( s)
{
var r = new bdccGeo(0,0);
r.x = this.x * s;
r.y = this.y * s;
r.z = this.z * s;
return r;
}
// More Maths
bdccGeo.prototype.crossNormalize = function( b)
{
var x = (this.y * b.z) - (this.z * b.y);
var y = (this.z * b.x) - (this.x * b.z);
var z = (this.x * b.y) - (this.y * b.x);
var L = Math.sqrt((x * x) + (y * y) + (z * z));
var r = new bdccGeo(0,0);
r.x = x / L;
r.y = y / L;
r.z = z / L;
return r;
}
// point on opposite side of the world to this point
bdccGeo.prototype.antipode = function()
{
return this.scale(-1.0);
}
//distance in radians from this point to point v2
bdccGeo.prototype.distance = function( v2)
{
return Math.atan2(v2.crossLength(this), v2.dot(this));
}
//returns in meters the minimum of the perpendicular distance of this point from the line segment geo1-geo2
//and the distance from this point to the line segment ends in geo1 and geo2
bdccGeo.prototype.distanceToLineSegMtrs = function(geo1, geo2)
{
//point on unit sphere above origin and normal to plane of geo1,geo2
//could be either side of the plane
var p2 = geo1.crossNormalize(geo2);
// intersection of GC normal to geo1/geo2 passing through p with GC geo1/geo2
var ip = bdccGeoGetIntersection(geo1,geo2,this,p2);
//need to check that ip or its antipode is between p1 and p2
var d = geo1.distance(geo2);
var d1p = geo1.distance(ip);
var d2p = geo2.distance(ip);
//window.status = d + ", " + d1p + ", " + d2p;
if ((d >= d1p) && (d >= d2p))
return bdccGeoRadiansToMeters(this.distance(ip));
else
{
ip = ip.antipode();
d1p = geo1.distance(ip);
d2p = geo2.distance(ip);
}
if ((d >= d1p) && (d >= d2p))
return bdccGeoRadiansToMeters(this.distance(ip));
else
return bdccGeoRadiansToMeters(Math.min(geo1.distance(this),geo2.distance(this)));
}
// distance in meters from GLatLng point to GPolyline or GPolygon poly
function bdccGeoDistanceToPolyMtrs(poly, point)
{
var d = 999999999;
var i;
var p = new bdccGeo(point.lat(),point.lng());
for(i=0; i<(poly.getPath().getLength()-1); i++)
{
var p1 = poly.getPath().getAt(i);
var l1 = new bdccGeo(p1.lat(),p1.lng());
var p2 = poly.getPath().getAt(i+1);
var l2 = new bdccGeo(p2.lat(),p2.lng());
var dp = p.distanceToLineSegMtrs(l1,l2);
if(dp < d)
d = dp;
}
return d;
}
// get a new GLatLng distanceMeters away on the compass bearing azimuthDegrees
// from the GLatLng point - accurate to better than 200m in 140km (20m in 14km) in the UK
function bdccGeoPointAtRangeAndBearing (point, distanceMeters, azimuthDegrees)
{
var latr = point.lat() * Math.PI / 180.0;
var lonr = point.lng() * Math.PI / 180.0;
var coslat = Math.cos(latr);
var sinlat = Math.sin(latr);
var az = azimuthDegrees* Math.PI / 180.0;
var cosaz = Math.cos(az);
var sinaz = Math.sin(az);
var dr = distanceMeters / 6378137.0; // distance in radians using WGS84 Equatorial Radius
var sind = Math.sin(dr);
var cosd = Math.cos(dr);
return new google.maps.LatLng(Math.asin((sinlat * cosd) + (coslat * sind * cosaz)) * 180.0 / Math.PI,
(Math.atan2((sind * sinaz), (coslat * cosd) - (sinlat * sind * cosaz)) + lonr) * 180.0 / Math.PI);
}
Credits to Bill Chadwick 2007 and Lawrence Ross 2014 for the v3 version. And #geocodezip for finding it.
JSFiddle demo

Limiting the great circle

I need to limit the radius of the great circle problem. The circle will extend until it hits another item.
I need it to limit the range of the circle to 5 miles
Here is my code
function find_closest_ticket(ticket, lat, lng) {
// var lat = map.position.coords.latitude;
// var lon = map.position.coords.longitude;
// lat = 24.709254;
// lng = -81.381927;
var R = 6371; // radius of earth in km
var distances = [];
var closest = -1;
for (i = 0; i < ticket.length; i++) {
var mlat = ticket[i].soLAT;
var mlng = ticket[i].soLNG;
var dLat = rad(mlat - lat);
var dLong = rad(mlng - lng);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
distances[i] = d;
if (closest == -1 || d < distances[closest]) {
closest = i;
}
}
return closest;
}
First, it is surprising you use a function that returns a radius in km, and then want to limit it to 5 miles. You should make up your mind: either write the function to return miles and add the limit in miles, or leave the function as-is and limit it by km (8 km is roughly 5 miles).
If you want to use miles, then change this line:
var R = 6371; // radius of earth in km
to:
var R = 3959; // radius of earth in miles
and replace:
return closest;
by:
return Math.min(5, closest);
Alternatively, if you want to stick to km, then only replace:
return closest;
by:
return Math.min(8, closest);

Javascript function order

I want to execute functions in order but i constantly get 1,3,4,2 in console.Because of that ltt and lott remains 0 in function getDistanceFromLatLonInKm.Any ideas?Thanks in advance.
var ltt=0;
var lott=0;
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(ajmo);
console.log('1');
}
function ajmo(position){
console.log('2');
window.ltt=position.coords.latitude;
window.lott=position.coords.longitude;
document.write(window.ltt);
}
console.log('3');
document.write(window.ltt);
document.write("kurac:" + getDistanceFromLatLonInKm(45.332497,14.436384));
function getDistanceFromLatLonInKm(lat1,lon1){
console.log('4');
//second
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(ltt-lat1); // deg2rad below
var dLon = deg2rad(lott-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(ltt)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
The following changes will ensure that all console messages are in order 1,2,3,4
var ltt=0;
var lott=0;
if (navigator.geolocation){
console.log('1');
navigator.geolocation.getCurrentPosition(ajmo);
}
function ajmo(position){
console.log('2');
window.ltt=position.coords.latitude;
window.lott=position.coords.longitude;
document.write(window.ltt);
console.log('3');
document.write(window.ltt);
document.write("kurac:" + getDistanceFromLatLonInKm(45.332497,14.436384));
}
function getDistanceFromLatLonInKm(lat1,lon1){
console.log('4');
//second
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(ltt-lat1); // deg2rad below
var dLon = deg2rad(lott-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(ltt)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
The reason why they are being called out of order is because the method "geolocation.getCurrentPosition(success, error, options)" is asynchronous.
https://developer.mozilla.org/en-US/docs/WebAPI/Using_geolocation
The (function)object AJMO that you are giving to it is actually used to describe the callback method. The script hits the line and sends an asynchronous request to the function, BUT it isn't going to wait for a response. The execution proceeds forward even though it hasn't heard back yet. The remaining lines are pretty simple with very low overhead so they resolve much, much quicker than the getCurrentPosition method. '2' is executed at the end, but this is only because the method finally "called back" to the success function you created, "AJMO".
If you want to make sure that the code is executed in order you could try this instead.
var ltt=0;
var lott=0;
function getDistanceFromLatLonInKm(lat1,lon1){
console.log('4');
//second
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(ltt-lat1); // deg2rad below
var dLon = deg2rad(lott-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(ltt)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function ajmo(position){
console.log('2');
window.ltt=position.coords.latitude;
window.lott=position.coords.longitude;
document.write(window.ltt);
console.log('3');
document.write("kurac:" + getDistanceFromLatLonInKm(45.332497,14.436384));
}
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(ajmo);
console.log('1');
}
This puts the calls to '2', '3', and '4' within the successful callback method while still exposing "getDistanceFromLatLonInKm" as a separate function if you need it for some other purpose.
You don't need to use global variables here. Simply include the call to getDistanceFromLatLonInKm within ajmo, and this will ensure that your code does things in the right order.
// call getLocation
getLocation();
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(ajmo);
}
}
function ajmo(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// don't use document.write - it's considered bad practice
// this will get access to an element with id="out"
var out = document.getElementById('out');
// now pass lat and lng as new parameters into getDistanceFromLatLonInKm
out.innerHTML = 'kurac:' + getDistanceFromLatLonInKm(45.332497, 14.436384, lat, lng);
}
// now use the lat/lng arguments instead of the global variables
function getDistanceFromLatLonInKm(lat_origin, lon_origin, lat_pos, lng_pos) {
var R = 6371;
var dLat = deg2rad(lat_pos - lat_origin);
var dLon = deg2rad(lng_pos - lng_origin);
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat_origin)) * Math.cos(deg2rad(lat_pos)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}

Google maps api v2 - find closest/nearest markers/points in the map ?

Hi i am trying do what seems to be almost impossible ... i am trying to get three nearest locations marker objects ... is this even possible ? .. it does not have to be 100% accurate ... but to do at least something ... what i found on the net and tried was this :
function find_closest_marker( lat1, lon1 ) {
for(var y = 1; y < 4; y++){
var pi = Math.PI;
var R = 6371; //equatorial radius
for(var i=0;i<markers.length; i++ ) {
//alert(markers.length);
var closest = -1;
var distances = [];
var lat2 = points[i].lat().toFixed(5);
var lon2 = points[i].lng().toFixed(5);
var chLat = lat2-lat1;
var chLon = lon2-lon1;
var dLat = chLat*(pi/180);
var dLon = chLon*(pi/180);
var rLat1 = lat1*(pi/180);
var rLat2 = lat2*(pi/180);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(rLat1) * Math.cos(rLat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
distances[i] = d;
if ( closest == -1 || d < distances[closest] ) {
closest = i;
}
}
var markerImg = "";
if(markers[closest].markerType == 1){
markerImg="/files/billeder/../Templates/Designs/Ideal2011/images/Map/dot_red.jpg"
} else if(markers[closest].markerType == 2){
markerImg="/files/billeder/../Templates/Designs/Ideal2011/images/Map/dot_lblue.jpg"
}else if(markers[closest].markerType == 3){
markerImg="/files/billeder/../Templates/Designs/Ideal2011/images/Map/dot_dblue.jpg"
}else if(markers[closest].markerType == 4){
markerImg="/files/billeder/../Templates/Designs/Ideal2011/images/Map/dot_green.jpg"
}
$('.nearestPlace'+y).html(
"<img src='"+markerImg+"' alt='"+markers[closest].address+"' />"+
"<div class='CompanyName'><strong>"+markers[closest].title+"</strong></div>"+
markers[closest].address+"<br/>"+
markers[closest].postby+"<br/>"+
"Tlf.: "+markers[closest].phone+"<br/>"+
markers[closest].fax+
markers[closest].web+
markers[closest].email
);
//markers.pop(markers[closest]);
//points.pop(points[closest]);
//markers[closest] = "";
//points[closest]= "";
//alert(closest);
//markers.slice(closest,closest+1);
//points.slice(closest,closest+1);
//alert(markers[closest].title)
delete markers[closest];
delete points[closest]
}
}
How you can see from some comments in the code i have tried many different things !! non of them seems to work for me ! It gives the first location (not even correct one) and then just breaks , does nothing for second and third ...
Can anyone see mistakes in this ? OR MAYBE EVEN BETTER KNOW OR CAN WRITE A CODE TO GET DESIRED FUNCTIONALITY ?
lat1, lon1 - of the current point !
i have 300 markers in not big area so there should not be difficult for script to find 3 nearest.
if you iterate through your markers you can call this method on each and then store the results in an array that you can sort the array. This is going to be a costly operation...
/**
* This will give you the distance in kilometers between 2 positions
*
* #param lat1 - The first positions latitude
* #param lng2 - The first positions longitude
* #param lat2 - The second positions latitide
* #param lng2 - The second positions longitude
*
* #return int- The distance in kilometers between the 2 places
*/
distanceFrom : function(lat1,lng1, lat2, lng2) {
var R = 6371; // km
var dLat = this._toRad((lat2-lat1));
var dLon = this._toRad((lng2-lng1));
var lat1 = this._toRad(lat1);
var lat2 = this._toRad(lat2);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}

Categories

Resources