Get visitor location using HTML5 Geolocation API and PHP

Many times you need to track the visitor’s location as per your web project requirement. In this tutorial we’ll show you the simplest way to getting the user current location. Using HTML5 and PHP, you can easily track your website visitor’s country, state, city, location, and zipcode.

The helping of HTML5 Geolocation API, you can get the geographical position of a visitor. But this will work if the visitor approves it. Once you get the visitor latitude and longitude by HTML5 Geolocation API, you can get the location from it by Google Maps API.


Using our simple script, you can be able to integrate visitor location tracking functionality in your project within 5 minutes. We’ll use only two files index.html and getLocation.php to get the visitor location.

index.html File

At first, we’ll get the visitor’s latitude and longitude using HTML5 Geolocation API. After that we’ll get the visitor’s address from the getLocation.php file using Ajax. Once the response is received from the getLocation.php file, we’ll display the visitor’s location into target (#location) area.

getCurrentPosition() method is used to get the visitor’s position. showLocation() method is used to getting the visitor’s address from getLocation.php file using Ajax.

<script src="jquery.min.js"></script>
    if (navigator.geolocation) {
    } else { 
        $('#location').html('Geolocation is not supported by this browser.');

function showLocation(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
                $("#location").html('Not Available');

The visitor’s location will be displayed at the #location span.

<p>Your Location: <span id="location"></span></p>

getLocation.php File

In this file we’ll get the address from latitude and longitude using Google Maps API. Then we’ll send the response into the Ajax success function.

if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
//Send request and receive json data by latitude and longitude
$url ''.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
$json = @file_get_contents($url);
$data json_decode($json);
$status $data->status;
//Get address from json data
$location $data->results[0]->formatted_address;
$location =  '';
//Print address 
echo $location;

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You


  1. Ankit Said...
  2. Mz Said...
  3. Uday Said...
  4. Mike Said...
  5. Pradeep Said...
  6. Moshiur Said...
  7. TAHA Said...
  8. Alpesh Solanki Said...
  9. Sudip Bhakat Said...
  10. Pawan Said...
  11. Isaac Said...
  12. Varun Said...
  13. Mohamed Adel Said...
  14. Danish Said...
    • CodexWorld Said...

Leave a reply