Get Visitor Location using HTML5 Geolocation API and PHP


Many web application tracks the geographical information of the visitor or user. Tracking the visitor’s location can be done by many ways. There are many third-party API services available to get the user location by IP address. These geolocation service providers charge for using their API. This tutorial shows how you can get the user location at free of cost using HTML Geolocation API.

get-user-location-from-browser-php-geolocation-api-coddexworld

The HTML5 Geolocation API helps to get geographical location of a user. You can locate the visitor’s position using HTML Geolocation API. But HTML Geolocation will provide the location if the user approves it. Otherwise, the user position will not be available. Once you get the visitor latitude and longitude by HTML5 Geolocation API, you can get the website visitor’s country, state, city, location, and zip code by Google Maps API.

In this tutorial, we will show you how to implement visitor location tracking functionality in the website using HTML Geolocation API and PHP. The following functionality will be implemented to get user location from browser using Geolocation API and PHP.

  • Get the latitude and longitude of the current user using HTML Geolocation API.
  • Get the location by latitude & longitude using Google Maps Geocoding API and PHP.

We will use two files (index.html and getLocation.php) to get the geographical location of the user.

index.html

At first, we will retrieve the visitor’s latitude and longitude using HTML5 Geolocation API. After that, we will send this latitude and longitude to the getLocation.php file using jQuery Ajax to get the visitor’s address. Once the response is received from the getLocation.php file, the visitor’s location will be displayed in the specified area (#location).

JavaScript Code:
The jQuery Ajax is used to post the latitude and longitude to PHP file. So, include the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

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

<script>
$(document).ready(function(){
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(showLocation);
    }else{ 
        $('#location').html('Geolocation is not supported by this browser.');
    }
});

function showLocation(position){
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    $.ajax({
        type:'POST',
        url:'getLocation.php',
        data:'latitude='+latitude+'&longitude='+longitude,
        success:function(msg){
            if(msg){
               $("#location").html(msg);
            }else{
                $("#location").html('Not Available');
            }
        }
    });
}
</script>

HTML Code:
After getting the visitor position, the address will be shown on the web page (#location span).

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

getLocation.php

In this file, the geographic coordinates (latitude and longitude) is converted into a human-readable address using Google Maps Geocoding API and PHP. Based on the latitude and longitude, the formatted_address is fetched and the response is sent to the Ajax success function.

<?php
//if latitude and longitude are submitted
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
    
//send request and receive json data by latitude and longitude
    
$url 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
    
$json = @file_get_contents($url);
    
$data json_decode($json);
    
$status $data->status;
    
    
//if request status is successful
    
if($status == "OK"){
        
//get address from json data
        
$location $data->results[0]->formatted_address;
    }else{
        
$location =  '';
    }
    
    
//return address to ajax 
    
echo $location;
}
?>

Browsers Support

All major browser supports HTML5 Geolocation. But as of Google Chrome 50, the HTML Geolocation API is no longer supported over HTTP. The getcurrentposition() and watchposition() are deprecated on insecure origins in Chrome 50. The Geolocation API will only work on secure origins such as HTTPS. You can check the more details about this issue from here.

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

Recommended Tutorials For You

19 Comments

  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