1

i am working on a gps tracking solution. But my problem is i have my geolocation but i want a way to go from my location to another location that I've previously defined. How can i do it ? I´m working with the Google Maps API

  • Hey buddy, You should look up some of Google Maps API tutorials, such as this guide from the MIT libraries : https://libraries.mit.edu/files/gis/Working%20with%20the%20Google%20Maps%20API.pdf – Rann Lifshitz Apr 28 '18 at 00:51

1 Answers1

0

You can use the Haversine Formula, like this:

Number.prototype.toRad = function() {
  return this * Math.PI / 180;
}

var Point = function(lat, lng){
  this.lat = lat;
  this.lng = lng;
}

var p1 = new Point(-23.6536633, -46.70669269999996);
var p2 = new Point(-23.5553565, -46.66189859999997);

var deltaLat = p2.lat - p1.lat;
var deltaLng = p2.lng - p1.lng;
var lat = deltaLat.toRad()/2;
var lng = deltaLng.toRad()/2;
var a = Math.sin(lat) * Math.sin(lat) + 
    Math.cos(p1.lat.toRad()) * Math.cos(p2.lat.toRad()) *
    Math.sin(lng) * Math.sin(lng);

var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
var distance = 6371 * c;
console.log(distance);

document.getElementById("demo").innerHTML = distance.toFixed(2) +" km";
<p id="demo"></p>

Inspired by this thread:

Using the Haversine Formula in Javascript

Edudjr
  • 1,676
  • 18
  • 28