Menu
calculate-distance-using-longitude-latitude-php

Calculate Distance From Latitude and Longitude PHP

PHP By Aug 23, 2015 2 Comments

Calculating distance from latitude and longitude is bit tricky and complex. Recently we were working on a project and we need to calculate the longitude and latitude from given longitude and latitude. We use to show the nearest restaurant’s using our location. We got success so i think to put it online so that it will help you guy’s. Soon we will put this example in most of the programming language. Right now it is in PHP.

Calculate Distance from Latitude and Longitude Using PHP

We have created a function for it and we are putting this function here.

public function calculateDistance($lat1, $lon1, $lat2, $lon2, $unit) {
    $radlat1 = pi() * $lat1/180;
        $radlat2 = pi() * $lat2/180;
        $theta = $lon1-$lon2;
        $radtheta = pi() * $theta/180;
        $dist = sin($radlat1) * sin($radlat2) + cos($radlat1) * cos($radlat2) * cos($radtheta);
        $dist = acos($dist);
        $dist = $dist * 180/  pi();
        $dist = $dist * 60 * 1.1515;
        if ($unit=="K") { $dist = $dist * 1.609344; }
        if ($unit=="N") { $dist = $dist * 0.8684; }
        return  $dist;
    }

It will take 5 parameter’s which are as follows.

  • $lat1 = Your Latitude
  • $lon1 = Your Longitude
  • $lat2 = Searched Latitude
  • $lon2 = Searched Longitude
  • $unit = K for kilometer, N for Nautical Miles, Leave it blank will show Miles.

Hope it will help you in your project and you like our tutorial. Please share it with other’s if you have any issue please let us know comment below it will be happy to help you. Thank You

~~~~Happy Coding~~~~

Author

Hello i am Vivek Moyal PHP developer and writes tutorials for students and beginners. Love to explore new cities

2 Comments

  1. Stan says:

    Are you sure this works? The distances being returned are way off….

    1. Vivek Moyal says:

      Yup its working as we are using this on an APP and its work’s perfect

Leave a comment

Your email address will not be published. Required fields are marked *