how to calculate location different from distance - javascript

i am new in gis. I am working in JavaScript.
suppose there is center latlong. another point is target(latlong) in n miters far from center. how to calculate this location difference(center - latlong) from center and n in miter.
guys please help me.
lets consider earth is properly spherical.

function distance(lat1, lon1, lat2, lon2) {
var radius = 6371e3; // meters
var dLon = gis.toRad(lon2 - lon1),
lat1 = gis.toRad(lat1),
lat2 = gis.toRad(lat2),
distance = Math.acos(Math.sin(lat1) * Math.sin(lat2) +
Math.cos(lat1) * Math.cos(lat2) * Math.cos(dLon)) * radius;
return distance;
}
above javascript function is for calculating distance,
function(lat, long, distance){
//can i calculate lat_difference, long difference
}

here is your code:-
<script>
Math.radians = function(degrees) {
return degrees * Math.PI / 180;
};
function calculateDistance(lat,lon,lat_center,lon_center){
var distance = ( 6371 * Math.acos( Math.cos( Math.radians(lat) ) * Math.cos( Math.radians( lat_center ) )
* Math.cos( Math.radians( lon_center ) - Math.radians(lon) ) + Math.sin( Math.radians(lat) ) * Math.sin(Math.radians(lat_center)) ) )*1000;
console.log(distance+" meter");
return distance;
}
var lat = '38.898556';
var lon = '-77.037852';
var lat_center = '38.897147';
var lon_center = '-77.043934';
calculateDistance(lat,lon,lat_center,lon_center);//will return 549 meter
//for getting lat and lon from a distance from a given point
//lat1 = latitude of start point in degrees
//long1 = longitude of start point in degrees
//d = distance in KM
//angle = bearing in degrees
function get_gps_distance(lat1,long1,d,angle)
{
//# Earth Radious in KM
var R = 6378.14;
//# Degree to Radian
var latitude1 = lat1 * (Math.PI/180);
var longitude1 = long1 * (Math.PI/180);
brng = angle * (Math.PI/180);
latitude2 = Math.asin(Math.sin(latitude1)*Math.cos(d/R) + Math.cos(latitude1)*Math.sin(d/R)*Math.cos(brng));
longitude2 = longitude1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(latitude1),Math.cos(d/R)-Math.sin(latitude1)*Math.sin(latitude2));
// # back to degrees
latitude2 = latitude2 * (180/Math.PI);
longitude2 = longitude2 * (180/Math.PI);
// # 6 decimal for Leaflet and other system compatibility
lat2 = latitude2;
long2 =longitude2;
var tab = {};
// Push in array and get back
tab[0] = lat2;
tab[1] = long2;
return tab;
}
get_gps_distance('38.898556','-77.037852',.549,90);
</script>

Related

javascript Latitude Longitude to xyz position on earth (threejs)

i´m playing arround with three.js
i want to render objects on specific geocoordinates on a bigger sphere, i´m pretty near to the solution, but i dont get the correct xyz position from lat lon
i have set up a test case on jsfiddle, there are two coordinates
latlons = [[40.7142700,-74.0059700], [52.5243700,13.4105300]];
its New York and Berlin
and this is my function to calc xyz from lat lon and radius
function calcPosFromLatLonRad(lat,lon,radius){
// Attempt1
var cosLat = Math.cos(lat * Math.PI / 180.0);
var sinLat = Math.sin(lat * Math.PI / 180.0);
var cosLon = Math.cos(lon * Math.PI / 180.0);
var sinLon = Math.sin(lon * Math.PI / 180.0);
var rad = radius;
y = rad * cosLat * sinLon;
x = rad * cosLat * cosLon;
z = rad * sinLat;
// Attempt2
// x = radius * Math.sin(lat) * Math.cos(lon)
// y = radius * Math.sin(lat) * Math.sin(lon)
// z = radius * Math.cos(lat)
// Attempt3
// latitude = lat * Math.PI/180
// longitude = lon * Math.PI/180
// x = -radius * Math.cos(latitude) * Math.cos(longitude)
// y = radius * Math.sin(latitude)
// z = radius * Math.cos(latitude) * Math.sin(longitude)
// Attempt4
// var phi = (90-lat)*(Math.PI/180);
// var theta = (lng+180)*(Math.PI/180);
// x = ((rad) * Math.sin(phi)*Math.cos(theta));
// z = ((rad) * Math.sin(phi)*Math.sin(theta));
// y = ((rad) * Math.cos(phi));
console.log([x,y,z]);
return [x,y,z];
}
but all attempts return different xy, and they are all not correct ( z is always correct).
could someone pleas guide me to the right way ?
i have no idea what could be wrong
heres the fiddle to play with
UPDATE: working jsfiddle
unfortunatly i can´t further explain, but after playing around this one works like a charme :)
function calcPosFromLatLonRad(lat,lon,radius){
var phi = (90-lat)*(Math.PI/180);
var theta = (lon+180)*(Math.PI/180);
x = -(radius * Math.sin(phi)*Math.cos(theta));
z = (radius * Math.sin(phi)*Math.sin(theta));
y = (radius * Math.cos(phi));
return [x,y,z];
}
yeah thats pretty cool isnt it ?
And i´m still interested into some shorter equation
working fiddle
This function works for me:
function calcPosFromLatLonRad(radius, lat, lon) {
var spherical = new THREE.Spherical(
radius,
THREE.Math.degToRad(90 - lon),
THREE.Math.degToRad(lat)
);
var vector = new THREE.Vector3();
vector.setFromSpherical(spherical);
console.log(vector.x, vector.y, vector.z);
return vector;
}
calcPosFromLatLonRad(0.5, -74.00597, 40.71427);

Draw circle's arc on google maps

The idea is to draw an arc centered on a specific point, using angles.
Note: Not the chord, nor the sector, nor the area between the chord and the arc.
Memento: http://en.wikipedia.org/wiki/Arc_(geometry)
A full circle parameters:
- center at coordinates LatC,LngC
- radius of 1 609 meters
- start angle of 0 degrees
- end angle of 360 degrees
example http://jsfiddle.net/GGvQH/3/
new google.maps.Circle({
center: new google.maps.LatLng(18.4894, 73.910158),
radius: 1609,
...
});
An arc of 180° (PI/2 radiant) oriented to north would be like:
- center at coordinates LatC,LngC
- radius of 1 609 meters
- start angle of 270 degrees (9 o'clock)
- end angle of 90 degrees (3 o'clock)
First of all, I do not want to plot a polyline for each arc, using tons of points to get a smooth effect: need to recompute for each scale and may cost resources... or is it?
There is an idea with polygons intersection
Google Maps API v3 - circle sector
...do anyone have seen a working jsfiddle?
Note: http://jsfiddle.net/Morlock0821/4dRB2/1/ is very close to the arc, but I do not want a closed surface.
Another idea with bearing... but I am reluctant to redefine the earth's radius to get the tiny arc I want.
https://developers.google.com/maps/documentation/javascript/examples/geometry-headings
(in this case, I want only the purple line, not the red one).
Any help would be greatly appreciated.
This is the code I use in this example:
function drawArc(center, initialBearing, finalBearing, radius) {
var d2r = Math.PI / 180; // degrees to radians
var r2d = 180 / Math.PI; // radians to degrees
var points = 32;
// find the raidus in lat/lon
var rlat = (radius / EarthRadiusMeters) * r2d;
var rlng = rlat / Math.cos(center.lat() * d2r);
var extp = new Array();
if (initialBearing > finalBearing) finalBearing += 360;
var deltaBearing = finalBearing - initialBearing;
deltaBearing = deltaBearing/points;
for (var i=0; (i < points+1); i++)
{
extp.push(center.DestinationPoint(initialBearing + i*deltaBearing, radius));
bounds.extend(extp[extp.length-1]);
}
return extp;
}
Used like this, where startPoint is the start of the arc, endPoint is the end of the arc and centerPoint is the center, but you can specify center, angles and radius.
var arcPts = drawArc(centerPoint, centerPoint.Bearing(startPoint), centerPoint.Bearing(endPoint), centerPoint.distanceFrom(startPoint));
var piePoly = new google.maps.Polygon({
paths: [arcPts],
strokeColor: "#00FF00",
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map
});
Ancillary functions, may no longer be necessary if you include the geometry library
var EarthRadiusMeters = 6378137.0; // meters
/* Based the on the Latitude/longitude spherical geodesy formulae & scripts
at http://www.movable-type.co.uk/scripts/latlong.html
(c) Chris Veness 2002-2010
*/
google.maps.LatLng.prototype.DestinationPoint = function (brng, dist) {
var R = EarthRadiusMeters; // earth's mean radius in meters
var brng = brng.toRad();
var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();
var lat2 = Math.asin( Math.sin(lat1)*Math.cos(dist/R) +
Math.cos(lat1)*Math.sin(dist/R)*Math.cos(brng) );
var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(dist/R)*Math.cos(lat1),
Math.cos(dist/R)-Math.sin(lat1)*Math.sin(lat2));
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
// === A function which returns the bearing between two LatLng in radians ===
// === If v1 is null, it returns the bearing between the first and last vertex ===
// === If v1 is present but v2 is null, returns the bearing from v1 to the next vertex ===
// === If either vertex is out of range, returns void ===
google.maps.LatLng.prototype.Bearing = function(otherLatLng) {
var from = this;
var to = otherLatLng;
if (from.equals(to)) {
return 0;
}
var lat1 = from.latRadians();
var lon1 = from.lngRadians();
var lat2 = to.latRadians();
var lon2 = to.lngRadians();
var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
if ( angle < 0.0 ) angle += Math.PI * 2.0;
if ( angle > Math.PI ) angle -= Math.PI * 2.0;
return parseFloat(angle.toDeg());
}
/**
* Extend the Number object to convert degrees to radians
*
* #return {Number} Bearing in radians
* #ignore
*/
Number.prototype.toRad = function () {
return this * Math.PI / 180;
};
/**
* Extend the Number object to convert radians to degrees
*
* #return {Number} Bearing in degrees
* #ignore
*/
Number.prototype.toDeg = function () {
return this * 180 / Math.PI;
};
/**
* Normalize a heading in degrees to between 0 and +360
*
* #return {Number} Return
* #ignore
*/
Number.prototype.toBrng = function () {
return (this.toDeg() + 360) % 360;
};
code snippet (using geometry library):
var EarthRadiusMeters = 6378137.0; // meters
/* Based the on the Latitude/longitude spherical geodesy formulae & scripts
at http://www.movable-type.co.uk/scripts/latlong.html
(c) Chris Veness 2002-2010
*/
google.maps.LatLng.prototype.DestinationPoint = function(brng, dist) {
var R = EarthRadiusMeters; // earth's mean radius in meters
var brng = brng.toRad();
var lat1 = this.lat().toRad(),
lon1 = this.lng().toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist / R) +
Math.cos(lat1) * Math.sin(dist / R) * Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist / R) * Math.cos(lat1),
Math.cos(dist / R) - Math.sin(lat1) * Math.sin(lat2));
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
/**
* Extend the Number object to convert degrees to radians
*
* #return {Number} Bearing in radians
* #ignore
*/
Number.prototype.toRad = function() {
return this * Math.PI / 180;
};
/**
* Extend the Number object to convert radians to degrees
*
* #return {Number} Bearing in degrees
* #ignore
*/
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
};
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
bounds.extend(latlng);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
function drawArc(center, initialBearing, finalBearing, radius) {
var d2r = Math.PI / 180; // degrees to radians
var r2d = 180 / Math.PI; // radians to degrees
var points = 32;
// find the raidus in lat/lon
var rlat = (radius / EarthRadiusMeters) * r2d;
var rlng = rlat / Math.cos(center.lat() * d2r);
var extp = new Array();
if (initialBearing > finalBearing) finalBearing += 360;
var deltaBearing = finalBearing - initialBearing;
deltaBearing = deltaBearing / points;
for (var i = 0;
(i < points + 1); i++) {
extp.push(center.DestinationPoint(initialBearing + i * deltaBearing, radius));
bounds.extend(extp[extp.length - 1]);
}
return extp;
}
function drawCircle(point, radius) {
var d2r = Math.PI / 180; // degrees to radians
var r2d = 180 / Math.PI; // radians to degrees
var EarthRadiusMeters = 6378137.0; // meters
var earthsradius = 3963; // 3963 is the radius of the earth in miles
var points = 32;
// find the raidus in lat/lon
var rlat = (radius / EarthRadiusMeters) * r2d;
var rlng = rlat / Math.cos(point.lat() * d2r);
var extp = new Array();
for (var i = 0; i < points + 1; i++) // one extra here makes sure we connect the
{
var theta = Math.PI * (i / (points / 2));
ey = point.lng() + (rlng * Math.cos(theta)); // center a + radius x * cos(theta)
ex = point.lat() + (rlat * Math.sin(theta)); // center b + radius y * sin(theta)
extp.push(new google.maps.LatLng(ex, ey));
bounds.extend(extp[extp.length - 1]);
}
// alert(extp.length);
return extp;
}
var map = null;
var bounds = null;
function initialize() {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(-33.9, 151.2),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
bounds = new google.maps.LatLngBounds();
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var startPoint = new google.maps.LatLng(48.610335003092956, -1.6123447775299600);
var endPoint = new google.maps.LatLng(48.596190206866830, -1.5551704322317228);
var centerPoint = new google.maps.LatLng(48.565630000000006, -1.6050300000000002);
createMarker(startPoint, "start: " + startPoint.toUrlValue(6) + "<br>distance to center: " + (google.maps.geometry.spherical.computeDistanceBetween(centerPoint, startPoint) / 1000).toFixed(3) + " km<br>Bearing: " + google.maps.geometry.spherical.computeHeading(centerPoint, startPoint) + "<br><a href='javascript:map.setCenter(new google.maps.LatLng(" + startPoint.toUrlValue(6) + "));map.setZoom(20);'>zoom in</a> - <a href='javascript:map.fitBounds(bounds);'>zoom out</a>");
createMarker(endPoint, "end: " + endPoint.toUrlValue(6) + "<br>distance to center: " + (google.maps.geometry.spherical.computeDistanceBetween(centerPoint, endPoint) / 1000).toFixed(3) + " km<br>Bearing: " + google.maps.geometry.spherical.computeHeading(centerPoint, endPoint) + "<br><a href='javascript:map.setCenter(new google.maps.LatLng(" + endPoint.toUrlValue(6) + "));map.setZoom(20);'>zoom in</a> - <a href='javascript:map.fitBounds(bounds);'>zoom out</a>");
createMarker(centerPoint, "center: " + centerPoint.toUrlValue(6));
var arcPts = drawArc(centerPoint, google.maps.geometry.spherical.computeHeading(centerPoint, startPoint), google.maps.geometry.spherical.computeHeading(centerPoint, endPoint), google.maps.geometry.spherical.computeDistanceBetween(centerPoint, startPoint));
// add the start and end lines
arcPts.push(centerPoint);
bounds.extend(centerPoint);
arcPts.push(startPoint);
var piePoly = new google.maps.Polygon({
paths: [arcPts],
strokeColor: "#00FF00",
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map
});
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=geometry"></script>
<div id="map_canvas"></div>

Geolocation closest location(lat, long) from my position

I want to show specific information depending on where i am.
I have five cities with different information, and i want to show that city(information) that i'm closest to.
How to i do that the simplest way, using javascript.
Ex.
If i store the cities lat, long in an array
var cities = [
['new york', '111111', '222222', 'blablabla']
['boston', '111111', '222222', 'blablabla']
['seattle', '111111', '222222', 'blablabla']
['london', '111111', '222222', 'blablabla']
]
And with my current location(lat, long) i want the city that i'm closet to.
Here is a basic code example using HTML5 geolocation to get the user's position. It then calls NearestCity() and calculates the distance (km) from the location to each city. I passed on using the Haversine formulae and instead used the simpler Pythagoras formulae and an equirectangular projection to adjust for the curvature in longitude lines.
// Get User's Coordinate from their Browser
window.onload = function() {
// HTML5/W3C Geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(UserLocation);
}
// Default to Washington, DC
else
NearestCity(38.8951, -77.0367);
}
// Callback function for asynchronous call to HTML5 geolocation
function UserLocation(position) {
NearestCity(position.coords.latitude, position.coords.longitude);
}
// Convert Degress to Radians
function Deg2Rad(deg) {
return deg * Math.PI / 180;
}
function PythagorasEquirectangular(lat1, lon1, lat2, lon2) {
lat1 = Deg2Rad(lat1);
lat2 = Deg2Rad(lat2);
lon1 = Deg2Rad(lon1);
lon2 = Deg2Rad(lon2);
var R = 6371; // km
var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
var y = (lat2 - lat1);
var d = Math.sqrt(x * x + y * y) * R;
return d;
}
var lat = 20; // user's latitude
var lon = 40; // user's longitude
var cities = [
["city1", 10, 50, "blah"],
["city2", 40, 60, "blah"],
["city3", 25, 10, "blah"],
["city4", 5, 80, "blah"]
];
function NearestCity(latitude, longitude) {
var minDif = 99999;
var closest;
for (index = 0; index < cities.length; ++index) {
var dif = PythagorasEquirectangular(latitude, longitude, cities[index][1], cities[index][2]);
if (dif < minDif) {
closest = index;
minDif = dif;
}
}
// echo the nearest city
alert(cities[closest]);
}
With HTML5, you can pull the location of the user and then compares this example using a Haversine function (function below taken from here):
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
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)
}
You can calculate the distance by latitude with your location and the cities locations. And find the shortest and draw. To calculate you can read more in http://www.movable-type.co.uk/scripts/latlong.html

How to find the angle between two locations defined by latitude or longitude using javascript? [duplicate]

I want to calculate the bearing from point 1 to point 2
The input format is 52.070564 - 4.407116
No matter what i try i cannot get an correct output.
The formula i use is :
// koers berekenen
var y = Math.sin(ln-ln1) * Math.cos(lt);
var x = Math.cos(lt1)*Math.sin(lt) -
Math.sin(lt1)*Math.cos(lt)*Math.cos(ln-ln1);
var radians = Math.atan2(y, x);
var bearing = Math.round(radians * (180/Math.PI));
/* >>>>>> original <<<<<<<
var y = Math.sin(λ2-λ1) * Math.cos(φ2);
var x = Math.cos(φ1)*Math.sin(φ2) -
Math.sin(φ1)*Math.cos(φ2)*Math.cos(λ2-λ1);
var brng = Math.atan2(y, x).toDegrees();
φ1,λ1 is the start point, φ2,λ2 the end point (Δλ is the difference in longitude)
*/
You can calculate bearing using this functions:
// Converts from degrees to radians.
function toRadians(degrees) {
return degrees * Math.PI / 180;
};
// Converts from radians to degrees.
function toDegrees(radians) {
return radians * 180 / Math.PI;
}
function bearing(startLat, startLng, destLat, destLng){
startLat = toRadians(startLat);
startLng = toRadians(startLng);
destLat = toRadians(destLat);
destLng = toRadians(destLng);
y = Math.sin(destLng - startLng) * Math.cos(destLat);
x = Math.cos(startLat) * Math.sin(destLat) -
Math.sin(startLat) * Math.cos(destLat) * Math.cos(destLng - startLng);
brng = Math.atan2(y, x);
brng = toDegrees(brng);
return (brng + 360) % 360;
}
start_latitude = 12.9389352
start_longitude = 77.6994306
stop_latitude = 12.939103
stop_longitude = 77.705825
var y = Math.sin(stop_longitude-start_longitude) * Math.cos(stop_latitude);
var x = Math.cos(start_latitude)*Math.sin(stop_latitude) -
Math.sin(start_latitude)*Math.cos(stop_latitude)*Math.cos(stop_longitude-start_longitude);
var brng = Math.atan2(y, x) * 180 / Math.PI;
alert("Bearing in degreee: " + brng);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Google Maps - Find nearest bus station (Places service) [duplicate]

When i click on map, which will be best way to find nearest marker or markers? is there some functions in api that will help me to do that?
it's google map api v3.
First you have to add the eventlistener
google.maps.event.addListener(map, 'click', find_closest_marker);
Then create a function that loops through the array of markers and uses the haversine formula to calculate the distance of each marker from the click.
function rad(x) {return x*Math.PI/180;}
function find_closest_marker( event ) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
var R = 6371; // radius of earth in km
var distances = [];
var closest = -1;
for( i=0;i<map.markers.length; i++ ) {
var mlat = map.markers[i].position.lat();
var mlng = map.markers[i].position.lng();
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;
}
}
alert(map.markers[closest].title);
}
This keeps track of the closest markers and alerts its title.
I have my markers as an array on my map object
You can use the computeDistanceBetween() method in the google.maps.geometry.spherical namespace.
I'd like to expand on Leor's suggestion and provide a working solution:
I'm using markers in a markers array e.g. var markers = [];.
Then let's have our position as something like var location = new google.maps.LatLng(51.99, -0.74);
Then we simply reduce our markers against the location we have like so:
markers.reduce(function (prev, curr) {
var cpos = google.maps.geometry.spherical.computeDistanceBetween(location.position, curr.position);
var ppos = google.maps.geometry.spherical.computeDistanceBetween(location.position, prev.position);
return cpos < ppos ? curr : prev;
}).position
What pops out is your closest marker LatLng object.
The formula above didn't work for me, but I used this without any issue. Pass your current location to the function, and loop through an array of markers to find the closest:
function find_closest_marker( lat1, lon1 ) {
var pi = Math.PI;
var R = 6371; //equatorial radius
var distances = [];
var closest = -1;
for( i=0;i<markers.length; i++ ) {
var lat2 = markers[i].position.lat();
var lon2 = markers[i].position.lng();
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;
}
}
// (debug) The closest marker is:
console.log(markers[closest]);
}
Are you aware of Mysql Spatial extensions?
You could use something like MBRContains(g1,g2).
Use computeDistanceBetween() Google map API method to calculate near marker between your location and markers list on google map.
Steps:-
Create marker on google map.
function addMarker(location) {
var marker = new google.maps.Marker({
title: 'User added marker',
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5
},
position: location,
map: map
});
}
On Mouse click create event for getting lat, long of your location and pass that to find_closest_marker().
function find_closest_marker(event) {
var distances = [];
var closest = -1;
for (i = 0; i < markers.length; i++) {
var d = google.maps.geometry.spherical.computeDistanceBetween(markers[i].position, event.latLng);
distances[i] = d;
if (closest == -1 || d < distances[closest]) {
closest = i;
}
}
alert('Closest marker is: ' + markers[closest].getTitle());
}
visit this link follow the steps. You will able to get nearer marker to your location.
Here is another function that works great for me, returns distance in kilometers:
function distance(lat1, lng1, lat2, lng2) {
var radlat1 = Math.PI * lat1 / 180;
var radlat2 = Math.PI * lat2 / 180;
var radlon1 = Math.PI * lng1 / 180;
var radlon2 = Math.PI * lng2 / 180;
var theta = lng1 - lng2;
var radtheta = Math.PI * theta / 180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist);
dist = dist * 180 / Math.PI;
dist = dist * 60 * 1.1515;
//Get in in kilometers
dist = dist * 1.609344;
return dist;
}

Categories

Resources