Calculate distance between 2 co-ordinates [duplicate] - javascript

How do you calculate the distance between two markers in Google maps V3? (Similar to the distanceFrom function inV2.)
Thanks..

If you want to calculate it yourself, then you can use the Haversine formula:
var rad = function(x) {
return x * Math.PI / 180;
};
var getDistance = function(p1, p2) {
var R = 6378137; // Earth’s mean radius in meter
var dLat = rad(p2.lat() - p1.lat());
var dLong = rad(p2.lng() - p1.lng());
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(p1.lat())) * Math.cos(rad(p2.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;
return d; // returns the distance in meter
};

There actually seems to be a method in GMap3. It's a static method of the google.maps.geometry.spherical namespace.
It takes as arguments two LatLng objects and will utilize a default Earth radius of 6378137 meters, although the default radius can be overridden with a custom value if necessary.
Make sure you include:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3&libraries=geometry"></script>
in your head section.
The call will be:
google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);

Example using GPS latitude/longitude of 2 points.
var latitude1 = 39.46;
var longitude1 = -0.36;
var latitude2 = 40.40;
var longitude2 = -3.68;
var distance = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(latitude1, longitude1), new google.maps.LatLng(latitude2, longitude2));

Just add this to the beginning of your JavaScript code:
google.maps.LatLng.prototype.distanceFrom = function(latlng) {
var lat = [this.lat(), latlng.lat()]
var lng = [this.lng(), latlng.lng()]
var R = 6378137;
var dLat = (lat[1]-lat[0]) * Math.PI / 180;
var dLng = (lng[1]-lng[0]) * Math.PI / 180;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat[0] * Math.PI / 180 ) * Math.cos(lat[1] * Math.PI / 180 ) *
Math.sin(dLng/2) * Math.sin(dLng/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return Math.round(d);
}
and then use the function like this:
var loc1 = new GLatLng(52.5773139, 1.3712427);
var loc2 = new GLatLng(52.4788314, 1.7577444);
var dist = loc2.distanceFrom(loc1);
alert(dist/1000);

//p1 and p2 are google.maps.LatLng(x,y) objects
function calcDistance(p1, p2) {
var d = (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
console.log(d);
}

Here is the c# implementation of the this forumula
public class DistanceAlgorithm
{
const double PIx = 3.141592653589793;
const double RADIO = 6378.16;
/// <summary>
/// This class cannot be instantiated.
/// </summary>
private DistanceAlgorithm() { }
/// <summary>
/// Convert degrees to Radians
/// </summary>
/// <param name="x">Degrees</param>
/// <returns>The equivalent in radians</returns>
public static double Radians(double x)
{
return x * PIx / 180;
}
/// <summary>
/// Calculate the distance between two places.
/// </summary>
/// <param name="lon1"></param>
/// <param name="lat1"></param>
/// <param name="lon2"></param>
/// <param name="lat2"></param>
/// <returns></returns>
public static double DistanceBetweenPlaces(
double lon1,
double lat1,
double lon2,
double lat2)
{
double dlon = Radians(lon2 - lon1);
double dlat = Radians(lat2 - lat1);
double a = (Math.Sin(dlat / 2) * Math.Sin(dlat / 2)) + Math.Cos(Radians(lat1)) * Math.Cos(Radians(lat2)) * (Math.Sin(dlon / 2) * Math.Sin(dlon / 2));
double angle = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
return (angle * RADIO) * 0.62137;//distance in miles
}
}

With google you can do it using the spherical api, google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);.
However, if the precision of a spherical projection or a haversine solution is not precise enough for you (e.g. if you're close to the pole or computing longer distances), you should use a different library.
Most information on the subject I found on Wikipedia here.
A trick to see if the precision of any given algorithm is adequate is to fill in the maximum and minimum radius of the earth and see if the difference might cause problems for your use case. Many more details can be found in this article
In the end the google api or haversine will serve most purposes without problems.

Using PHP, you can calculate the distance using this simple function :
// to calculate distance between two lat & lon
function calculate_distance($lat1, $lon1, $lat2, $lon2, $unit='N')
{
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
// function ends here

OFFLINE SOLUTION - Haversine Algorithm
In Javascript
var _eQuatorialEarthRadius = 6378.1370;
var _d2r = (Math.PI / 180.0);
function HaversineInM(lat1, long1, lat2, long2)
{
return (1000.0 * HaversineInKM(lat1, long1, lat2, long2));
}
function HaversineInKM(lat1, long1, lat2, long2)
{
var dlong = (long2 - long1) * _d2r;
var dlat = (lat2 - lat1) * _d2r;
var a = Math.pow(Math.sin(dlat / 2.0), 2.0) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r) * Math.pow(Math.sin(dlong / 2.0), 2.0);
var c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
var d = _eQuatorialEarthRadius * c;
return d;
}
var meLat = -33.922982;
var meLong = 151.083853;
var result1 = HaversineInKM(meLat, meLong, -32.236457779983745, 148.69094705162837);
var result2 = HaversineInKM(meLat, meLong, -33.609020205923713, 150.77061469270831);
C#
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var meLat = -33.922982;
double meLong = 151.083853;
var result1 = HaversineInM(meLat, meLong, -32.236457779983745, 148.69094705162837);
var result2 = HaversineInM(meLat, meLong, -33.609020205923713, 150.77061469270831);
Console.WriteLine(result1);
Console.WriteLine(result2);
}
static double _eQuatorialEarthRadius = 6378.1370D;
static double _d2r = (Math.PI / 180D);
private static int HaversineInM(double lat1, double long1, double lat2, double long2)
{
return (int)(1000D * HaversineInKM(lat1, long1, lat2, long2));
}
private static double HaversineInKM(double lat1, double long1, double lat2, double long2)
{
double dlong = (long2 - long1) * _d2r;
double dlat = (lat2 - lat1) * _d2r;
double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
double d = _eQuatorialEarthRadius * c;
return d;
}
}
Reference:
https://en.wikipedia.org/wiki/Great-circle_distance

Had to do it... The action script way
//just make sure you pass a number to the function because it would accept you mother in law...
public var rad = function(x:*) {return x*Math.PI/180;}
protected function distHaversine(p1:Object, p2:Object):Number {
var R:int = 6371; // earth's mean radius in km
var dLat:Number = rad(p2.lat() - p1.lat());
var dLong:Number = rad(p2.lng() - p1.lng());
var a:Number = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c:Number = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d:Number = R * c;
return d;
}

In my case it was best to calculate this in SQL Server, since i wanted to take current location and then search for all zip codes within a certain distance from current location. I also had a DB which contained a list of zip codes and their lat longs. Cheers
--will return the radius for a given number
create function getRad(#variable float)--function to return rad
returns float
as
begin
declare #retval float
select #retval=(#variable * PI()/180)
--print #retval
return #retval
end
go
--calc distance
--drop function dbo.getDistance
create function getDistance(#cLat float,#cLong float, #tLat float, #tLong float)
returns float
as
begin
declare #emr float
declare #dLat float
declare #dLong float
declare #a float
declare #distance float
declare #c float
set #emr = 6371--earth mean
set #dLat = dbo.getRad(#tLat - #cLat);
set #dLong = dbo.getRad(#tLong - #cLong);
set #a = sin(#dLat/2)*sin(#dLat/2)+cos(dbo.getRad(#cLat))*cos(dbo.getRad(#tLat))*sin(#dLong/2)*sin(#dLong/2);
set #c = 2*atn2(sqrt(#a),sqrt(1-#a))
set #distance = #emr*#c;
set #distance = #distance * 0.621371 -- i needed it in miles
--print #distance
return #distance;
end
go
--get all zipcodes within 2 miles, the hardcoded #'s would be passed in by C#
select *
from cityzips a where dbo.getDistance(29.76,-95.38,a.lat,a.long) <3
order by zipcode

//JAVA
public Double getDistanceBetweenTwoPoints(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {
final int RADIUS_EARTH = 6371;
double dLat = getRad(latitude2 - latitude1);
double dLong = getRad(longitude2 - longitude1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getRad(latitude1)) * Math.cos(getRad(latitude2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return (RADIUS_EARTH * c) * 1000;
}
private Double getRad(Double x) {
return x * Math.PI / 180;
}

/**
* Calculates the haversine distance between point A, and B.
* #param {number[]} latlngA [lat, lng] point A
* #param {number[]} latlngB [lat, lng] point B
* #param {boolean} isMiles If we are using miles, else km.
*/
function haversineDistance(latlngA, latlngB, isMiles) {
const squared = x => x * x;
const toRad = x => (x * Math.PI) / 180;
const R = 6371; // Earth’s mean radius in km
const dLat = toRad(latlngB[0] - latlngA[0]);
const dLon = toRad(latlngB[1] - latlngA[1]);
const dLatSin = squared(Math.sin(dLat / 2));
const dLonSin = squared(Math.sin(dLon / 2));
const a = dLatSin +
(Math.cos(toRad(latlngA[0])) * Math.cos(toRad(latlngB[0])) * dLonSin);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let distance = R * c;
if (isMiles) distance /= 1.609344;
return distance;
}
I found a version online which is 80% right but plugged in the wrong parameter and is inconsistent in using the inputs, this version fixed that completely

It's Quite easy using Google Distance Matrix service
First step is to activate Distance Matrix service from google API console.
it returns distances between a set of locations.
And apply this simple function
function initMap() {
var bounds = new google.maps.LatLngBounds;
var markersArray = [];
var origin1 = {lat:23.0203, lng: 72.5562};
//var origin2 = 'Ahmedabad, India';
var destinationA = {lat:23.0436503, lng: 72.55008939999993};
//var destinationB = {lat: 23.2156, lng: 72.6369};
var destinationIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=O|FFFF00|000000';
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 55.53, lng: 9.4},
zoom: 10
});
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: [destinationA],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
deleteMarkers(markersArray);
var showGeocodedAddressOnMap = function(asDestination) {
var icon = asDestination ? destinationIcon : originIcon;
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
markersArray.push(new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
}));
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
geocoder.geocode({'address': originList[i]},
showGeocodedAddressOnMap(false));
for (var j = 0; j < results.length; j++) {
geocoder.geocode({'address': destinationList[j]},
showGeocodedAddressOnMap(true));
//outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] + ': ' + results[j].distance.text + ' in ' + results[j].duration.text + '<br>';
outputDiv.innerHTML += results[j].distance.text + '<br>';
}
}
}
});
}
Where origin1 is your location and destinationA is destindation location.you can add above two or more data.
Rad Full Documentation with an example

To calculate distance on Google Maps, you can use Directions API. That will be one of the easiest way to do it. To get data from Google Server, you can use Retrofit or Volley. Both has their own advantage. Take a look at following code where I have used retrofit to implement it:
private void build_retrofit_and_get_response(String type) {
String url = "https://maps.googleapis.com/maps/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitMaps service = retrofit.create(RetrofitMaps.class);
Call<Example> call = service.getDistanceDuration("metric", origin.latitude + "," + origin.longitude,dest.latitude + "," + dest.longitude, type);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Response<Example> response, Retrofit retrofit) {
try {
//Remove previous line from map
if (line != null) {
line.remove();
}
// This loop will go through all the results and add marker on each location.
for (int i = 0; i < response.body().getRoutes().size(); i++) {
String distance = response.body().getRoutes().get(i).getLegs().get(i).getDistance().getText();
String time = response.body().getRoutes().get(i).getLegs().get(i).getDuration().getText();
ShowDistanceDuration.setText("Distance:" + distance + ", Duration:" + time);
String encodedString = response.body().getRoutes().get(0).getOverviewPolyline().getPoints();
List<LatLng> list = decodePoly(encodedString);
line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(20)
.color(Color.RED)
.geodesic(true)
);
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
Above is the code of function build_retrofit_and_get_response for calculating distance. Below is corresponding Retrofit Interface:
package com.androidtutorialpoint.googlemapsdistancecalculator;
import com.androidtutorialpoint.googlemapsdistancecalculator.POJO.Example;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;
public interface RetrofitMaps {
/*
* Retrofit get annotation with our URL
* And our method that will return us details of student.
*/
#GET("api/directions/json?key=AIzaSyC22GfkHu9FdgT9SwdCWMwKX1a4aohGifM")
Call<Example> getDistanceDuration(#Query("units") String units, #Query("origin") String origin, #Query("destination") String destination, #Query("mode") String mode);
}
I hope this explains your query. All the best :)
Source: Google Maps Distance Calculator

First, are you referring to distance as in length of the entire path or you want to know only the displacement (straight line distance)? I see no one is pointing the difference between distance and displacement here. For distance calculate each route point given by JSON/XML data, as for displacement there is a built-in solution using Spherical class
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}

In PHP, with Google Map Distance Matrix API:
//Get the Driving(Mode) distance between two Geo-location points(Latitude, Longitude) pair.
function get_distance($lat1, $lat2, $long1, $long2)
{
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving"."&units=imperial";
//You can request distance data for different travel modes, request distance data in different units such as kilometers or miles, and estimate travel time in traffic.
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response, true);
//Invalid request OR Empty response
if(isset($response_a['error_message']) || empty($response_a['rows']))
throw new Exception($response_a['error_message']);
} catch(Exception $e){
//Handle error here.
return [];
}
//The unit parameter in the request URL only affects the text displayed within distance fields. The distance fields in response also contain values that are always expressed in meters.
$dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
$time = $response_a['rows'][0]['elements'][0]['duration']['text'];
return ['distance' => $dist, 'time' => $time];
}
Reference: Distance Matrix API request and response

Related

Geolocation doesn't update my walked distance

Hi I'm creating an walk tracker webapp by usiing geolocation with javascript. Everything works fine except the part when I have to calculate the distance by using the old latlong with new latlong.
The Code:
function updateLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var timestamp = position.timestamp;
document.getElementById("latitude").innerHTML = latitude;
document.getElementById("longitude").innerHTML = longitude;
document.getElementById("accuracy").innerHTML = accuracy.toFixed(2) + " meter";
document.getElementById("timestamp").innerHTML = new Date(timestamp).toLocaleString();
if (accuracy >= 500) {
updateStatus("Need more accurate values to calculate distance.");
return;
}
if ((lastLat != null) && (lastLong != null)) {
var currentDistance = distance(latitude, longitude, lastLat, lastLong);
document.getElementById("currDist").innerHTML =
"Current distance traveled: " + currentDistance.toFixed(2) + " km";
totalDistance += currentDistance;
document.getElementById("totalDist").innerHTML =
"Total distance traveled: " + currentDistance.toFixed(2) + " km";
}
lastLat = latitude;
lastLong = longitude;
updateStatus("Location successfully updated.");
}
Added the distance function*
Number.prototype.toRadians = function() {
return this * Math.PI / 180;
}
function distance(latitude1, longitude1, latitude2, longitude2) {
// R is the radius of the earth in kilometers
var R = 6371;
var deltaLatitude = (latitude2-latitude1).toRadians();
var deltaLongitude = (longitude2-longitude1).toRadians();
latitude1 = latitude1.toRadians(), latitude2 = latitude2.toRadians();
var a = Math.sin(deltaLatitude/2) *
Math.sin(deltaLatitude/2) +
Math.cos(latitude1) *
Math.cos(latitude2) *
Math.sin(deltaLongitude/2) *
Math.sin(deltaLongitude/2);
var c = 2 * Math.atan2(Math.sqrt(a),
Math.sqrt(1-a));
var d = R * c;
return d;
}
Hope someone can find what Im doing wrong.
Thank you
Update:
I found the problem why geolocation didn't update my distance.. it's because the variable lastlong and lastlat which I declared didn't gave me the previous location, it gave me the current location of latitude and longitude which I declared inside updateLocation and assign lastlat and last long with those variable.
My question is now how can I calculate the previous location with the
new location, can't find any solution for it.
New Update:
Found my solution for this problem. For calculating the previous
distance I store the coords in a array and get the last position to
calculate the distance with the current position.
Code:
var coords = []; var distance = 0.0;
function calculateDistance(fromPos, toPos) {
var radius = 6371;
var toRad = function(number) {
return number * Math.PI / 180;
};
var latDistance = toRad(toPos.latitude - fromPos.latitude);
var lonDistance = toRad(toPos.longitude - fromPos.longitude);
var a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) +
Math.cos(toRad(fromPos.latitude)) * Math.cos(toRad(toPos.latitude)) *
Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
return radius * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));
}
var lastPos = coords[coords.length-1];
if(lastPos) {
distance += calculateDistance(lastPos, position.coords);
document.getElementById("currDist").innerHTML =
"Current distance traveled: " + distance.toFixed(2) + " km";
}
coords.push(position.coords);
One thing that I not understand is why my timestamp inside my array is undefined? Because the lat and long can I get easy without problem.
For a complete working journey logger example please see Google Drive or GitHub.
Pay attention to the filterLocation function in TravelManagerPolyfil.js as you might just be getting many zero distance readings and need to throttle watchPosition.
This code works: -
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var perthLat = 31.9505;
var perthLon = 115.8605;
var freoLat = 32.0569;
var freoLon = 115.7439;
const EARTH_RADIUS = 6378137;
var toRad =
function (num) {
return num * Math.PI / 180;
};
var calculateDistance =
function(lat1, lon1, lat2, lon2){
var dLat = toRad(lat2 - lat1);
var dLon = toRad(lon2 - lon1);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this.toRad(lat1)) *
Math.cos(toRad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
var distance = EARTH_RADIUS * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return distance;
}
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Distance = " +
calculateDistance(perthLat, perthLon,
freoLat, freoLon) / 1000;
}
</script>
</body>
</html>

Sorting by distance with Titanium alloy models

I recently used Titanium and Alloy to develop an android application. Now I'm trying (for the first time) to sort a bound backbone collection by distance with a comparator function, but it doesn't work.
comparator: function(game) {
var lon1, lat1, lat2, lon2;
if (Ti.Geolocation.locationServicesEnabled) {
Ti.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
Ti.API.error('Error:' + e.error);
return 0;
} else {
Ti.API.info(e.coords);
lon1 = e.coords.longitude;
lat1 = e.coords.latitude;
Titanium.Geolocation.forwardGeocoder(game.get("camp"), function(e) {
if (e.success) {
lat2 = e.latitude;
lon2 = e.longitude;
var R = 6371; // km
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;
console.log("KM: " + parseInt(d));
return parseInt(d);
} else {
console.log("Unable to find address");
return 0;
}
});
}
});
} else {
console.log('please enable location services')
return 0;
}
}
In my controller, I use:
var games = Alloy.Collections.allGames;
games.sort();
games.fetch();
Can you tell me what is wrong?
I don't use neither Titanium or Alloy, but I can see why your comparator function won't work.
Backbone collection's comparator property
First, to see why it doesn't work, you need to understand what's the collection's comparator property, what's available and how to implement one.
There are (at least) 3 types of value a collection's comparator property can take.
The name of an attribute as a string
comparator: 'fieldName'
A sortBy function which takes a single argument
comparator: function(model) {
// return a numeric or string value by which the model
// should be ordered relative to others.
return Math.sin(model.get('myNumber'));
}
A sort function that expects two arguments
comparator: compare(modelA, modelB) {
var field = 'myNumber',
numA = modelA.get(field),
numB = modelB.get(field);
if (numA < numB) {
return -1;
}
if (numA > numB) {
return 1;
}
// a must be equal to b
return 0;
}
Why yours fails?
The short answer: It only ever returns undefined or 0 depending on the value of Ti.Geolocation.locationServicesEnabled.
You have made a convoluted function to sort your models in which you use asynchronous functions (getCurrentPosition, forwardGeocoder) and you put all the logic inside callbacks which are evaluated when the collection has already finished sorting.

error retrieving distance and travel time values from a Google API ()

im not sure what approach to take next with this, currently I have this below code which calculates the distance in miles between any 2 given locations (using long and lat), however its a straight line, and roads aren't straight... so what I want to do is calculate a distance as google maps would, for example here are some random co-ordinates:
lat1: 53.015036674593500
lat2: -2.244633982337860
long1: 52.363731052413800
long2: -1.307122733526320
and when cast into this code (JavaScript)
function distance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1 / 180
var radlat2 = Math.PI * lat2 / 180
var radlon1 = Math.PI * lon1 / 180
var radlon2 = Math.PI * lon2 / 180
var theta = lon1 - lon2
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
if (unit == "K") { dist = dist * 1.609344 }
if (unit == "N") { dist = dist * 0.8684 }
return dist
}
var dist = distance(lata, longa, latb, longb, unit).toFixed(2);
window.alert(dist + " miles");
the value returned is 59.83 miles or there abouts... where if i was to do this in google maps:
https://www.google.co.uk/maps/dir/1+Creswell+Pl,+Cawston,+Rugby+CV22+7GZ,+UK/1+Ironbridge+Dr,+Newcastle+ST5+6ER,+UK/#52.6863234,-2.0253047,10z/data=!3m1!4b1!4m13!4m12!1m5!1m1!1s0x487747659759ff6f:0x2ae7f451f320ca80!2m2!1d-1.3071227!2d52.3637323!1m5!1m1!1s0x487a67f1ebd6bdaf:0x89c3b0d334683e52!2m2!1d-2.2446339!2d53.0150378
the values range between 77.1 miles and 76.5 miles
The Question
I have the BELOW function PARTLY working to get the travel time and distance, however it randomly returns "UNDEFINED" in the alert box at the bottom, or has this error message
"Object doesn't support this action"
when using the console.log it returns this message:
"google.maps.DistanceMatrixService is not a function"
code:
var siteP = postcodearray.indexOf(screen.sitePostcode);
var StaffP = postcodearray.indexOf(screen.engineerPostcode);
sitelat = latarray[siteP];
sitelong = longarray[siteP];
stafflat = latarray[StaffP];
stafflong = longarray[StaffP];
var site = sitelat + ", " + sitelong;
var staff = stafflat + ", " + stafflong;
var distance;
var duration;
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [staff],
destinations: [site],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
distance = response.rows[0].elements[0].distance.text;
duration = response.rows[0].elements[0].duration.text;
//var dvDistance = document.getElementById("dvDistance");
//dvDistance.innerHTML = "";
//dvDistance.innerHTML += "Distance: " + distance + "<br />";
//dvDistance.innerHTML += "Duration:" + duration;
} else {
alert("Unable to find the distance via road.");
}
});
window.alert(distance); //UNDEFINED
Please can someone point out what I have done/am doing wrong here as im so close to getting the 2 values I need
You can find an example of using the Bing Maps REST services to calculate a route between to locations in JavaScript here: https://msdn.microsoft.com/en-us/library/gg427607.aspx
I recommend adding the routeAttributes parameter and setting it to routeSummariesOnly. This will make the response really small. https://msdn.microsoft.com/en-us/library/ff701717.aspx
Alternatively, if you are using JavaScript and want to load a map, then use the Bing Maps JavaScript control and the directions module: https://msdn.microsoft.com/en-us/library/hh312802.aspx
You can also find an interactive SDK for the Bing Maps control here: https://www.bingmapsportal.com/ISDK/AjaxV7#CreateMap1
You will need a Bing Maps key to access the service, but it doesn't have to be tied to a refer. I recommend signing up for a free Bing Maps key here: https://azure.microsoft.com/en-us/marketplace/partners/bingmaps/mapapis/

Calculation geolocation distance returns NaN

I am trying to work out the distance between a user and the coordinates below, I am not sure what I have done wrong, but I get the response 'NaN' (not a number)
HTML:
<h3>Come visit</h3>
<p>You're only <span class="distance"> </span>km away</p>
JS File:
// Location
if($('#content').hasClass('contact_page')) {
var localSearch = new GlocalSearch();
var sharp_hq = {
lat: 53.639993,
lng: -1.782354
};
// calculate the distance between me and thee
var calculate_distance = function(location) {
return Math.round(3959 * 1.609344
* Math.acos(Math.cos(0.0174532925 * location.y)
* Math.cos(0.0174532925 * sharp_hq.lat)
* Math.cos((0.0174532925 * sharp_hq.lng) - (location.x * 0.0174532925))
+ Math.sin(0.0174532925 * location.y)
* Math.sin(0.0174532925 * sharp_hq.lat)));
};
// geo location
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//display in .distance <span>
$('.distance', '.location').html(calculate_distance(initialLocation));
$('p', '.location').css({ display: 'block' });
});
}
}
this works for me;
$(document).ready(function(){
var sharp_hq = {
lat: 53.639993,
lng: -1.782354
};
// geo location
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$('.distance').html( gc(position.coords.latitude,position.coords.longitude,sharp_hq.lat,sharp_hq.lng).toFixed(2) );
$('p', '.location').css({ display: 'block' });
});
}
} ) ;
/** Converts numeric degrees to radians */
if (typeof (Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function () {
return this * (Math.PI / 180);
}
};
function gc(lat1, lon1, lat2, lon2) {
// returns the distance in km between the pair of latitude and longitudes provided in decimal degrees
var R = 6371; // km
var dLat = (lat2 - lat1).toRad();
var dLon = (lon2 - lon1).toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
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;
}
A google.maps.LatLng object doesn't have .x or .y properties
Looks like you might still be expecting the Google Maps Javascript API v2 to work (it has been replaced by a wrapper for v3).
Instead of location.x/location.y use location.lat() for the latitude and location.lng() for the longitude. Or make your own anonymous object with .x and .y properties (but don't expect it to be interchangeable with a google.maps.LatLng object).
Note: the Google Maps Javascript API v3 has a library to calculate distance.
You can use a function called google.maps.geometry.computeDistanceBetween() that finds the distance between two latlng objects.
https://developers.google.com/maps/documentation/javascript/geometry
Replace the call to the calculate_distance function with
var distance = google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(sharp_hq.lat, sharphq.lng),
initialLocation
) / 1000;
$('.distance').text(distance);
Returns the distance in meters so divide by 1000.
In your formula, the value of (0.0174532925 * sharp_hq.lng) - (location.x * 0.0174532925) could be < 0 causing NaN.
You need to pre-process it to 0 if it is <0 to avoid the exception.
I wish this resolves your issue without changing the whole formula.

How to add markers on Google Maps polylines based on distance along the line?

I am trying to create a Google Map where the user can plot the route he walked/ran/bicycled and see how long he ran. The GPolyline class with it’s getLength() method is very helpful in this regard (at least for Google Maps API V2), but I wanted to add markers based on distance, for example a marker for 1 km, 5 km, 10 km, etc., but it seems that there is no obvious way to find a point on a polyline based on how far along the line it is. Any suggestions?
Having answered a similar problem a couple of months ago on how to tackle this on the server-side in SQL Server 2008, I am porting the same algorithm to JavaScript using the Google Maps API v2.
For the sake of this example, let's use a simple 4-point polyline, with a total length of circa 8,800 meters. The snippet below will define this polyline and will render it on the map:
var map = new GMap2(document.getElementById('map_canvas'));
var points = [
new GLatLng(47.656, -122.360),
new GLatLng(47.656, -122.343),
new GLatLng(47.690, -122.310),
new GLatLng(47.690, -122.270)
];
var polyline = new GPolyline(points, '#f00', 6);
map.setCenter(new GLatLng(47.676, -122.343), 12);
map.addOverlay(polyline);
Now before we approach the actual algorithm, we will need a function that returns the destination point when given a start point, an end point, and the distance to travel along that line, Luckily, there are a few handy JavaScript implementations by Chris Veness at Calculate distance, bearing and more between Latitude/Longitude points.
In particular I have adapted the following two methods from the above source to work with Google's GLatLng class:
Destination point given distance and bearing from start point
Bearing
These were used to extend Google's GLatLng class with a method moveTowards(), which when given another point and a distance in meters, it will return another GLatLng along that line when the distance is travelled from the original point towards the point passed as a parameter.
GLatLng.prototype.moveTowards = function(point, distance) {
var lat1 = this.lat().toRad();
var lon1 = this.lng().toRad();
var lat2 = point.lat().toRad();
var lon2 = point.lng().toRad();
var dLon = (point.lng() - this.lng()).toRad();
// Find the bearing from this point to the next.
var brng = Math.atan2(Math.sin(dLon) * Math.cos(lat2),
Math.cos(lat1) * Math.sin(lat2) -
Math.sin(lat1) * Math.cos(lat2) *
Math.cos(dLon));
var angDist = distance / 6371000; // Earth's radius.
// Calculate the destination point, given the source and bearing.
lat2 = Math.asin(Math.sin(lat1) * Math.cos(angDist) +
Math.cos(lat1) * Math.sin(angDist) *
Math.cos(brng));
lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angDist) *
Math.cos(lat1),
Math.cos(angDist) - Math.sin(lat1) *
Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
return new GLatLng(lat2.toDeg(), lon2.toDeg());
}
Having this method, we can now tackle the problem as follows:
Iterate through each point of the path.
Find the distance between the current point in the iteration to the next point.
If the distance in point 2 is greater the distance we need to travel on the path:
...then the destination point is between this point and the next. Simply apply the moveTowards() method to the current point, passing the next point and the distance to travel. Return the result and break the iteration.
Else:
...the destination point is further in the path from the next point in the iteration. We need to subtract the distance between this point and the next point from the total distance to travel along the path. Continue through the iteration with the modified distance.
You may have noticed that we can easily implement the above recursively, instead of iteratively. So let's do it:
function moveAlongPath(points, distance, index) {
index = index || 0; // Set index to 0 by default.
if (index < points.length) {
// There is still at least one point further from this point.
// Construct a GPolyline to use its getLength() method.
var polyline = new GPolyline([points[index], points[index + 1]]);
// Get the distance from this point to the next point in the polyline.
var distanceToNextPoint = polyline.getLength();
if (distance <= distanceToNextPoint) {
// distanceToNextPoint is within this point and the next.
// Return the destination point with moveTowards().
return points[index].moveTowards(points[index + 1], distance);
}
else {
// The destination is further from the next point. Subtract
// distanceToNextPoint from distance and continue recursively.
return moveAlongPath(points,
distance - distanceToNextPoint,
index + 1);
}
}
else {
// There are no further points. The distance exceeds the length
// of the full path. Return null.
return null;
}
}
With the above method, if we define an array of GLatLng points, and we invoke our moveAlongPath() function with this array of points and with a distance of 2,500 meters, it will return a GLatLng on that path at 2.5km from the first point.
var points = [
new GLatLng(47.656, -122.360),
new GLatLng(47.656, -122.343),
new GLatLng(47.690, -122.310),
new GLatLng(47.690, -122.270)
];
var destinationPointOnPath = moveAlongPath(points, 2500);
// destinationPointOnPath will be a GLatLng on the path
// at 2.5km from the start.
Therefore all we need to do is to call moveAlongPath() for each check point we need on the path. If you need three markers at 1km, 5km and 10km, you can simply do:
map.addOverlay(new GMarker(moveAlongPath(points, 1000)));
map.addOverlay(new GMarker(moveAlongPath(points, 5000)));
map.addOverlay(new GMarker(moveAlongPath(points, 10000)));
Note however that moveAlongPath() may return null if we request a check point further from the total length of the path, so it will be wiser to check for the return value before passing it to new GMarker().
We can put this together for the full implementation. In this example we are dropping a marker every 1,000 meters along the 8.8km path defined earlier:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps - Moving point along a path</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 500px; height: 300px;"></div>
<script type="text/javascript">
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
}
GLatLng.prototype.moveTowards = function(point, distance) {
var lat1 = this.lat().toRad();
var lon1 = this.lng().toRad();
var lat2 = point.lat().toRad();
var lon2 = point.lng().toRad();
var dLon = (point.lng() - this.lng()).toRad();
// Find the bearing from this point to the next.
var brng = Math.atan2(Math.sin(dLon) * Math.cos(lat2),
Math.cos(lat1) * Math.sin(lat2) -
Math.sin(lat1) * Math.cos(lat2) *
Math.cos(dLon));
var angDist = distance / 6371000; // Earth's radius.
// Calculate the destination point, given the source and bearing.
lat2 = Math.asin(Math.sin(lat1) * Math.cos(angDist) +
Math.cos(lat1) * Math.sin(angDist) *
Math.cos(brng));
lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angDist) *
Math.cos(lat1),
Math.cos(angDist) - Math.sin(lat1) *
Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
return new GLatLng(lat2.toDeg(), lon2.toDeg());
}
function moveAlongPath(points, distance, index) {
index = index || 0; // Set index to 0 by default.
if (index < points.length) {
// There is still at least one point further from this point.
// Construct a GPolyline to use the getLength() method.
var polyline = new GPolyline([points[index], points[index + 1]]);
// Get the distance from this point to the next point in the polyline.
var distanceToNextPoint = polyline.getLength();
if (distance <= distanceToNextPoint) {
// distanceToNextPoint is within this point and the next.
// Return the destination point with moveTowards().
return points[index].moveTowards(points[index + 1], distance);
}
else {
// The destination is further from the next point. Subtract
// distanceToNextPoint from distance and continue recursively.
return moveAlongPath(points,
distance - distanceToNextPoint,
index + 1);
}
}
else {
// There are no further points. The distance exceeds the length
// of the full path. Return null.
return null;
}
}
var map = new GMap2(document.getElementById('map_canvas'));
var points = [
new GLatLng(47.656, -122.360),
new GLatLng(47.656, -122.343),
new GLatLng(47.690, -122.310),
new GLatLng(47.690, -122.270)
];
var polyline = new GPolyline(points, '#f00', 6);
var nextMarkerAt = 0; // Counter for the marker checkpoints.
var nextPoint = null; // The point where to place the next marker.
map.setCenter(new GLatLng(47.676, -122.343), 12);
// Draw the path on the map.
map.addOverlay(polyline);
// Draw the checkpoint markers every 1000 meters.
while (true) {
// Call moveAlongPath which will return the GLatLng with the next
// marker on the path.
nextPoint = moveAlongPath(points, nextMarkerAt);
if (nextPoint) {
// Draw the marker on the map.
map.addOverlay(new GMarker(nextPoint));
// Add +1000 meters for the next checkpoint.
nextMarkerAt += 1000;
}
else {
// moveAlongPath returned null, so there are no more check points.
break;
}
}
</script>
</body>
</html>
Screenshot of the above example, showing a marker every 1,000 meters:
These are the prototypes for the required functions:
google.maps.Polygon.prototype.Distance = function() {
var dist = 0;
for (var i=1; i < this.getPath().getLength(); i++) {
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i-1));
}
return dist;
}
google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
//var R = 6371; // km (change this constant to get miles)
var R = 6378100; // meters
var lat1 = this.lat();
var lon1 = this.lng();
var lat2 = newLatLng.lat();
var lon2 = newLatLng.lng();
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;
return d;
}
source
Possibly the best approach would be to calculate where these points are.
As a basic algorithm you could iterate over all the points in the Polyline, and calculate the cumulative distance - if the next segment puts you over your distance, you can interpolate the point where the distance has been reached - then simply add a point of interest to your map for that.
I have used Martin Zeitler method to work with Google Map V3 and its working fine.
function init() {
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(-6.208437004433984, 106.84543132781982),
suppressInfoWindows: true,
};
// Get all html elements for map
var mapElement = document.getElementById('map1');
// Create the Google Map using elements
map = new google.maps.Map(mapElement, mapOptions);
var nextMarkerAt = 0; // Counter for the marker checkpoints.
var nextPoint = null; // The point where to place the next marker.
while (true) {
var routePoints = [ new google.maps.LatLng(47.656, -122.360),
new google.maps.LatLng(47.656, -122.343),
new google.maps.LatLng(47.690, -122.310),
new google.maps.LatLng(47.690, -122.270)];
nextPoint = moveAlongPath(routePoints, nextMarkerAt);
if (nextPoint) {
//Adding marker from localhost
MarkerIcon = "http://192.168.1.1/star.png";
var marker = new google.maps.Marker
({position: nextPoint,
map: map,
icon: MarkerIcon
});
// Add +1000 meters for the next checkpoint.
nextMarkerAt +=1000;
}
else {
// moveAlongPath returned null, so there are no more check points.
break;
}
}
}
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
Number.prototype.toDeg = function () {
return this * 180 / Math.PI;
}
function moveAlongPath(point, distance, index) {
index = index || 0; // Set index to 0 by default.
var routePoints = [];
for (var i = 0; i < point.length; i++) {
routePoints.push(point[i]);
}
if (index < routePoints.length) {
// There is still at least one point further from this point.
// Construct a GPolyline to use the getLength() method.
var polyline = new google.maps.Polyline({
path: [routePoints[index], routePoints[index + 1]],
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
// Get the distance from this point to the next point in the polyline.
var distanceToNextPoint = polyline.Distance();
if (distance <= distanceToNextPoint) {
// distanceToNextPoint is within this point and the next.
// Return the destination point with moveTowards().
return moveTowards(routePoints, distance,index);
}
else {
// The destination is further from the next point. Subtract
// distanceToNextPoint from distance and continue recursively.
return moveAlongPath(routePoints,
distance - distanceToNextPoint,
index + 1);
}
}
else {
// There are no further points. The distance exceeds the length
// of the full path. Return null.
return null;
}
}
function moveTowards(point, distance,index) {
var lat1 = point[index].lat.toRad();
var lon1 = point[index].lng.toRad();
var lat2 = point[index+1].lat.toRad();
var lon2 = point[index+1].lng.toRad();
var dLon = (point[index + 1].lng - point[index].lng).toRad();
// Find the bearing from this point to the next.
var brng = Math.atan2(Math.sin(dLon) * Math.cos(lat2),
Math.cos(lat1) * Math.sin(lat2) -
Math.sin(lat1) * Math.cos(lat2) *
Math.cos(dLon));
var angDist = distance / 6371000; // Earth's radius.
// Calculate the destination point, given the source and bearing.
lat2 = Math.asin(Math.sin(lat1) * Math.cos(angDist) +
Math.cos(lat1) * Math.sin(angDist) *
Math.cos(brng));
lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angDist) *
Math.cos(lat1),
Math.cos(angDist) - Math.sin(lat1) *
Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
google.maps.Polyline.prototype.Distance = function () {
var dist = 0;
for (var i = 1; i < this.getPath().getLength(); i++) {
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
return dist;
}
google.maps.LatLng.prototype.distanceFrom = function (newLatLng) {
//var R = 6371; // km (change this constant to get miles)
var R = 6378100; // meters
var lat1 = this.lat();
var lon1 = this.lng();
var lat2 = newLatLng.lat();
var lon2 = newLatLng.lng();
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;
return d;
}
I wanted to port Daniel Vassalo's answer to iOS, but it wasn't worked properly and some markers were misplaced until I changed
var dLon = (point.lng() - this.lng()).toRad();
to
var dLon = point.lng().toRad() - this.lng().toRad();
So if anyone having a trouble to figure out why are the markers are misplaced, try this and maybe it will help.

Categories