Skip to main content

How calculate the distance between two latitudes and longitudes using the Haversine formula

The Haversine formula is a formula used to calculate the great-circle distance (the shortest distance on a sphere between two points) between two points, usually specified in terms of their latitudes and longitudes. It is commonly used in navigation and is named after the haversine function, which is used in its calculation.

The Haversine formula is:

d = 2r arcsin(sqrt(sin²((lat₂ - lat₁)/2) + cos(lat₁) * cos(lat₂) * sin²((lon₂ - lon₁)/2)))


  • d is the distance between the two points in the same units as the radius r
  • lat₁, lon₁ are the latitude and longitude, respectively, of the first point in radians
  • lat₂, lon₂ are the latitude and longitude, respectively, of the second point in radians
  • r is the radius of the sphere

Note that this formula assumes that the Earth is a perfect sphere, which is not exactly true but is a close enough approximation for many practical purposes.

In PHP, the Haversine formula can be implemented using the sin, cos, sqrt, asin, deg2rad, and rad2deg functions to perform the necessary trigonometric calculations.

Here's an example PHP class that can calculate the distance between two latitudes and longitudes using the Haversine formula:

class DistanceCalculator {
    public function calculateDistance($lat1, $lon1, $lat2, $lon2, $unit = "km") {
        $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 == "KM") {
            return ($miles * 1.609344);
        } else if ($unit == "NM") {
            return ($miles * 0.8684);
        } else {
            return $miles;

The calculateDistance the method takes in four parameters - the latitude and longitude of the first point and the latitude and longitude of the second point. An optional fifth parameter allows you to specify the unit of measurement for the distance calculation (defaults to kilometers).

The method then uses the Haversine formula to calculate the distance between the two points and returns the result in the specified unit of measurement.


Popular posts from this blog

Learn how to setup push notifications in your Ionic app and send a sample notification using Node.js and PHP.

Ionic is an open source mobile UI toolkit for building modern, high quality cross-platform mobile apps from a single code base. To set up push notifications in your Ionic app, you will need to perform the following steps: Create a new Firebase project or use an existing one, and then enable Firebase Cloud Messaging (FCM) for your project. Install the Firebase Cloud Messaging plugin for Ionic: npm install @ionic-native/firebase-x --save Add the plugin to your app's app.module.ts file: import { FirebaseX } from '@ionic-native/firebase-x/ngx' ; @ NgModule({ ... providers: [ ... FirebaseX ... ] ... }) Initialize Firebase in your app's app.component.ts file: import { FirebaseX } from '@ionic-native/firebase-x/ngx' ; @ Component({ ... }) export class AppComponent { constructor ( private firebase : FirebaseX ) { this .firebase.init(); } } Register your app with Firebase Cloud Messaging by adding

How to export php/html page to Excel,Word & CSV file format

This class can generate the necessary request headers to make the outputted HTML be downloaded as a file by the browser with a file name that makes the file readable by Excel(.xls),Word(.doc) and CSV(.csv). Step1: Create PHP file named 'ExportPHP.class.php' ExportPHP.class.php <?php class ExportPHP { // method for Excel file function setHeaderXLS ( $file_name ) { header( "Content-type: application/ms-excel" ); header( "Content-Disposition: attachment; filename=$file_name" ); header( "Pragma: no-cache" ); header( "Expires: 0" ); } // method for Doc file function setHeaderDoc ( $file_name ) { header( "Content-type: application/x-ms-download" ); header( "Content-Disposition: attachment; filename=$file_name" ); header( 'Cache-Control: public' ); } // method for CSV file function setHeaderCSV (

Why is Apollo Client a crucial tool for your GraphQL project?

Apollo Client is a popular JavaScript library for managing GraphQL queries and mutations in client-side applications. There are several reasons why you might want to use Apollo Client in your GraphQL application: Simplified data management : With Apollo Client, you can easily manage your application's data with a single, declarative API. This can help to simplify your code and make it easier to reason about. Real-time updates : Apollo Client includes built-in support for subscriptions, which allow you to receive real-time updates from your GraphQL server. This can be useful for applications that require real-time data, such as chat applications or real-time analytics dashboards. Caching and performance : Apollo Client includes a sophisticated caching system that can help to improve the performance of your application by reducing the number of network requests required to fetch data. The cache can also be configured to automatically invalidate data when it becomes stale, ensuring th