Get current visitor's location using HTML5 Geolocation API and PHP

In this article, you will learn how to track the visitor's current location using PHP. For this, we are using the HTML5 Geolocation API. The HTML5 Geolocation API is used to get visitor's latitude and longitude and helps us to easily trace the visitor's full address (location, city, district, state, pincode), but this is possible only when the user click on the allow button of notification to share their current location. This notification is basically for privacy reason.

How to get current visitor's location using HTML5 Geolocation API and PHP

Here is the simple code written in HTML5, PHP and Javascript to get current visitor's location. HTML5 Geolocation API is responsible to work on secure context and provides visitor's latitude and longitude. After that, we will call the Ajax file 'get_location.php' and pass the latitude and longitude to get the visitor's address.





So, let's first create a file name 'index.php' and call the jQuery library file in the head section as we have mentioned here. In the body section, we have created two javascript functions - getlocation() and visitorLocation(). The getlocation() function is called on click the 'Get Current Location' button and visitorLocation() function is called within it to get the latitude and longitude.

var lat = position.coords.latitude;
var long = position.coords.longitude;

After the above code, we have called the ajax file 'get_location.php' and passed the 'lat' and 'long' variables as parameters to the url.

1. index.php

<!DOCTYPE>
<html>
    <head>
        <title>Get Visitor's Current Location using PHP and JQuery</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <style type="text/css">
            #container{ color:  #116997; border: 2px solid #0b557b; border-radius: 5px;}
            p{ font-size: 15px; font-weight: bold;}
        </style>
    </head>
    <body>
        <script type="text/javascript">
            function getlocation() {
                if (navigator.geolocation) { 
                    if(document.getElementById('location').innerHTML == '') {
                        navigator.geolocation.getCurrentPosition(visitorLocation);
                    } 
                } else { 
                    $('#location').html('This browser does not support Geolocation Service.');
                }
            }
            function visitorLocation(position) {
                var lat = position.coords.latitude;
                var long = position.coords.longitude;
                $.ajax({
                    type:'POST',
                    url:'get_location.php',
                    data:'latitude='+lat+'&longitude='+long,
                    success:function(address){
                        if(address){
                           $("#location").html(address);
                        }else{
                            $("#location").html('Not Available');
                        }
                    }
                });
            }
        </script>
        <input type="button" onclick="return getlocation()" value="Get Current Location" />
        <div id="container"><p>Your Current Location: <span id="location"></span></p></div>
    </body>
</html>
    

Then create another php file name 'get_location.php' and copy and paste the below code.





2. get_location.php


<?php
    if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
        //Send request and receive 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($status=="OK"){
            $location = $data->results[0]->formatted_address;
        }else{
            $location =  'No location found.';
        }
        echo $location; 
    } 
?>

In the above code, first we have requested the Geocoding API in the following format, which returns the output in JSON format.

https://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';

Then, we have used the file_get_contents() to read the contents of the JSON file as a string and decode this using json_decode() function.

$json = @file_get_contents($url);
$data = json_decode($json);

And finally, we have received the current visitor's location address in the following variable -

$location = $data->results[0]->formatted_address;




Related Articles

Get Visitor's location and TimeZone
How to use google map street view api on webpage
How to add multiple custom markers on google map
How to add google map on your website with marker
Create pie chart using google api
Driving route directions from source to destination using HTML5 and Javascript
Calculate the distance between two locations using PHP
Simple star rating system using PHP, jQuery and Ajax




Read more articles


General Knowledge



Learn Popular Language