Skip to content
Advertisement

calculate distance between two coordinates in javascript?

I am trying to calculate distance between two lats and longs in KM and show that distance in label or paragraph.

  • I have an address from which I need to figure out lat1 and lon1. I am able to figure this out.
  • I need to find lat2 and lon2 of my current location. I am able to figure this out as well.

Now once I have lat1, lon1, lat2 and lon2 – I need to find distance between these coordinates. Below is my code but it is giving distance as NaN once I alert it. I am not sure what’s wrong here. Also is this the right way I am doing here?

<!DOCTYPE html>
<html>
<style>
body {
  margin: 0;
  padding: 0;
  font: 12px sans-serif;
}
h1, p {
  margin: 0;
  padding: 0;
}
#map_div{
    width:400px;
    height:400px;
    margin: 0 auto;
}
#outer {
    width:400px;
    height:50px;
    margin:0 auto;
    text-align:center;
}
#outer input[type="text"] {
    display: block;
    margin: 0 auto;
}

</style>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&amp;sensor=false"></script>

<div id="outer">
<p id="distance_text">this is 201 km away from</p>
<input type="text" name="location" value="Current Location"><br>
<div id="map_div"></div>
</div>

</body>
<script type="text/javascript">
var lat1;
var lon1;
var lat2;
var lon2;
var geocoder = new google.maps.Geocoder();
var address = "1750 riverside drive, ottawa, ontario, canada";

geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
    lat1 = results[0].geometry.location.lat();
    lon1 = results[0].geometry.location.lng();
    }
});

var x = document.getElementById("distance_text");
getLocation();
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    lat2 = position.coords.latitude;
    lon2 = position.coords.longitude;
}
var distance = getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2);
alert(distance);
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);
  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)
}
</script>
</html>

I need to replace 201 km with actual distance after calculating it. Here is my jsfiddle

Advertisement

Answer

You can use google maps distance method but it require LatLng objects

Try this:

const from = new google.maps.LatLng(lat1, lng1);
const to = new google.maps.LatLng(lat2, lng2);
const distance =  google.maps.geometry.spherical.computeDistanceBetween(from,to)

This is the working JSfiddle You may have to add API key in map script tag: https://jsfiddle.net/ruokyanv/

change p tag distance: yes you can inject js file in your html and use jquery $:

var distance = `this is ${distance} km away from`
$('#distance_text').val(distance)

Let me know if the issue still persists.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement