etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Calculate distance between two locations using PHP

In this article, we will introduce a simple example to calculate distance between two locations using the PHP programming language and the Google Map API.

JSON format by sending a request to the Google map geocode api. The distance calculation is helpful when your web application works with the user's location. The Google Maps Geocoding API helps to easily calculate the distance between two locations from latitude and longitude in kilometres or miles.

Calculate the distance between two locations using PHP

This is the main file, that we will call in the browser. This file contains two input boxes to enter source and destination addresses and a selection option to select the unit.

When the user clicks on the submit button, the getRouteDistance() method will be called. This function calls the Google API and gets the latitude and longitude of the entered addresses from json_encode and calculates the distance between them.





The getRouteDistance() function accepts three parameters-

  • $source_adrs - Required, Source address.
  • $dest_adrs - Required, Destination address.
  • $unit - Optional, the default unit is miles.

To use the Google Maps Geocoding API, you need to specify the API Key in your request. Before getting started, go to Google Cloud Platform Console for Geocoding API and generate an API key.



index.php

<!DOCTYPE html>
<html>
   <head>
       <title>Calculate the distance between two locations</title>
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
       <style type="text/css">
            .formbg { background-color: #66CCFF; padding: 10px 0 10px 20px; color: #191919;
                    border-radius: 10px;  border: 2px solid #6D0839; width: 780px; margin: 0 auto;
            }
	   label { font-size: 18px; }
	   h1 {color: #003366;}
       </style>
   </head>

   <body>
      <?php 
      function getRouteDistance($source_adrs, $dest_adrs, $unit){

          // Your API Key
          $apiKey = 'Your_Google_API_Key';

          //Send request and receive json data
          // Geocoding API request with source address
          $s_geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$source_adrs.'&sensor=false&key='.$apiKey');
          $s_latlong = json_decode($s_geocode);

          // Geocoding API request with destinationaddress
          $d_geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$dest_adrs.'&sensor=false&key='.$apiKey');
          $d_latlong = json_decode($d_geocode);

          //Get latitude and longitude
          $lat1 = $s_latlong->results[0]->geometry->location->lat;
          $long1 = $s_latlong->results[0]->geometry->location->lng;
          $lat2 = $d_latlong->results[0]->geometry->location->lat;
          $long2 = $d_latlong->results[0]->geometry->location->lng;

          //Calculate the distance from latitude and longitude
          $theta = $long1 - $long2;
          $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);

          // Convert unit and return distance
          if ($unit == "K") {
              return ($miles * 1.609344).' KM';
          } else {
              return $miles.' MI';
          }
      } 
      ?>
      <div class="form-group row formbg">
          <?php

          // display the distance between locations on web page
          if(($_POST['source'] != '') && ($_POST['destination'] != '')) {
              $source = $_POST['source'];
              $destination = $_POST['destination'];
              $unit = $_POST['unit'];
              $source_adrs = str_replace(' ', '+', $source);
              $dest_adrs = str_replace(' ', '+', $destination);
              $distance = getRouteDistance($source_adrs, $dest_adrs, $unit);
              if($distance != '') {
                echo 'Distance Between <b>'.$source.'</b> and <b>'.$destination.' : </b><b>'.$distance.'</b>'
                    .'<br/><br/>';
              }
          }
          ?>

          <form action="" method="post">
             <div class="form-group row">
                <label class="col-xs-3 col-form-label">Enter Source Address: </label>
                <div class="col-xs-5">
                 <input class="form-control" type="text" name="source" value="" placeholder="Source">
                </div>
             </div>
             <div class="form-group row">
                <label class="col-xs-3 col-form-label">Enter Destination Address: </label>
                <div class="col-sm-5">
                 <input class="form-control" type="text" name="destination" value="" placeholder="Destination">
                </div>
              </div>
              <div class="form-group row">
                 <label class="col-xs-3 col-form-label">Unit: </label>
                 <div class="col-sm-5">
                  <select name="unit" class="form-control">
                      <option value="k">Kilometer</option>
                      <option value="m">Mile</option>
                  </select>
              </div>
             </div>
             <div class="form-group row">
                 <label class="col-xs-3 col-form-label"> </label>
                  <div class="col-sm-5">
                   <input class="btn btn-primary" type="submit" value="Submit"/>
                  </div>
                </div>
          </form>
      </div>
 </body>
</html>




Related Articles

How to insert image in database using PHP
PHP code to send SMS to mobile from website
PHP User Authentication by IP Address
PHP calculate percentage of total
How to lock a file using PHP
PHP remove last character from string
PHP User Authentication by IP Address
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP code to send email using SMTP
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to add multiple custom markers on google map
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP MYSQL Advanced Search Feature
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple PHP File Cache
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
Simple way to send SMTP mail using Node.js
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
Get Visitor\'s location and TimeZone
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP Programming Error Types
-----------------
Date Timestamp Formats in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.