×


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

In this post, you will learn how to track the visitor's current location using the PHP programming language.

Geolocation in itself is an innovation that has saved, served, and recommended incredible things, places to individuals all throughout the planet. By using geolocation, we can easily know how to go from one place to another. It can easily provide us with information, entertainment, security or weather updates.





For implementing this, we are using the HTML5 Geolocation API. The HTML5 Geolocation API is used to get the 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 clicks on the allow button of notification to share their current location. This notification is basically for privacy reasons.

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

Here is the simple code written in HTML5, PHP, and JavaScript to get the current visitor's location. The HTML5 Geolocation API is responsible for working in a secure context and providing visitors with their 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 named '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 when you click the 'Get Current Location' button and the 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 named 'get_location.php' and copy and paste the given 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 request 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

PHP reverse a string without predefined function
PHP random quote generator
PHP convert string into an array
PHP remove HTML and PHP tags from string
Import Excel File into MySQL using PHP
PHP array length
Import Excel File into MySQL Database using PHP
PHP String Contains
PHP remove last character from string
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
Preventing Cross Site Request Forgeries(CSRF) in PHP
Recover forgot password using PHP and MySQL
How to add google reCAPTCHA v2 in registration form using PHP
Complete HTML Form Validation in PHP
Submit a form data without page refresh using PHP, Ajax and Javascript




Read more articles


General Knowledge



Learn Popular Language