Sling Academy
Home/JavaScript/Calculate Distances and Routes in JavaScript via Geolocation

Calculate Distances and Routes in JavaScript via Geolocation

Last updated: December 12, 2024

With the increasing capabilities of modern browsers, JavaScript has become a powerful tool for tracking and calculating distances and creating routes directly from web applications. In this article, we will explore how you can leverage JavaScript’s Geolocation API and various libraries to calculate distances and routes with ease.

Understanding the Geolocation API

The Geolocation API allows the user's location to be accessed through JavaScript code. While it doesn't calculate distances by itself, it provides a latitude and longitude that can be used to calculate the distance between points.

Accessing User Location

Before accessing location data, ensure you have the user's consent, as acquiring location data is subject to privacy policies and browser permissions.


navigator.geolocation.getCurrentPosition(successCallback, errorCallback);

function successCallback(position) {
  const latitude = position.coords.latitude;
  const longitude = position.coords.longitude;
  console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
}

function errorCallback(error) {
  console.error(`Error code: ${error.code}, message: ${error.message}`);
}

The above code snipped successfully fetches the current geographical position of the user's device.

Calculating Distance

Once you have the coordinates, you can calculate the distance between two points using the Haversine formula. This formula calculates the shortest path over the earth's surface.

Implementing Haversine Formula


function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
  const R = 6371; // Radius of the earth in km
  const dLat = deg2rad(lat2 - lat1);
  const dLon = deg2rad(lon2 - lon1);
  const 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); 
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = R * c; // Distance in km
  return distance;
}

function deg2rad(deg) {
  return deg * (Math.PI / 180);
}

// Example usage
const distance = getDistanceFromLatLonInKm(51.5, -0.1, 38.8, -77.1);
console.log(`Distance: ${distance} km`);

The function getDistanceFromLatLonInKm accepts coordinates and returns the distance between them in kilometers.

Creating Routes

To create routes between two or more locations, it's best to use online maps services APIs such as Google Maps API or OpenStreetMap with Leaflet.js. These provide comprehensive functionality for rendering and showing paths.

Using the Google Maps API





function initMap() {
  const origin = { lat: 40.712776, lng: -74.005974 };
  const destination = { lat: 34.052235, lng: -118.243683 };
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 5,
    center: origin
  });

  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer();
  directionsRenderer.setMap(map);

  const request = {
    origin: origin,
    destination: destination,
    travelMode: 'DRIVING'
  };

  directionsService.route(request, function(result, status) {
    if (status === 'OK') {
      directionsRenderer.setDirections(result);
    }
  });
}

This API inclusion provides a complete map rendering along with a visually drawn route from the origin to the destination.

Conclusion

By utilizing the Geolocation API, you can successfully obtain location data from users, calculate distances using mathematical formulas, and visualize routes through sophisticated mapping services. This particularly enhances user experience in applications that necessitate geographical and map-driven functions.

Next Article: Enhance Personalized Content Using the Geolocation API in JavaScript

Previous Article: Provide Location-Based Features with the JavaScript Geolocation API

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration