A Blog about latest jobs updates, trending topics and different ways of earning money online.

How to calculate distance between two coordinates without map API in PHP

How to calculate distance between two coordinates without map API in PHP

In our last post we explain how to get distance and time between two coordinates using google map api in php. but google map api require credit card info hence its free but they require it and if some one do not want to share his card details or some one doesn't have card or for any reason someone want to find distance between two coordinates in php without using google map api then the following code is useful for him.

See how to calculate distance using MAP API

This code actually fine displacement not road distance but if you are working on sales man problem or some other like this this method is very useful.
here is the demonstration of how to find distance between two point in PHP using Haversine formula without using any Google map API.
code to calculate distance in php
code is below this function require 5 arguments.

  1. first is origin latitude
  2. second is origin longitude
  3. third is destination latitude
  4. forth is destination longitude
  5. fifth is distance unit like K for kilometer,M for miles
Distance function:


public function distance($lat1, $lon1, $lat2, $lon2, $unit) {

          $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 == "K") {
              return ($miles * 1.609344);
          } else if ($unit == "N") {
              return ($miles * 0.8684);
          } else {
              return $miles;
          }
    }


Previous
Next Post »

Popular posts