Get Visitor's location and TimeZone

In this article, you will learn how to get visitor's current location and timezome 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.

Get Visitor's location and TimeZone



Here is the simple code written in HTML5, PHP and Javascript to get current visitor's location. For this, we have created two files index.php and get_location.php. In 'index.php', the getlocation() function gets the visitor's current position and the visitorLocation() calls the Ajax file 'get_location.php' and pass the latitude and longitude to get the visitor's address. The GoogleMapsTimeZone is used to get Time Zone information for given latitude and longitude pair.


1.index.php

<!DOCTYPE html>
<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>


2. get_location.php

<?php
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
        require_once ('GoogleMapsTimeZone.php');
        //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.';
        }
        $status = $data->status;
        if($status=="OK"){
            $location = $data->results[0]->formatted_address;
        }else{
            $location =  'No location found.';
        }
        // Initialize GoogleMapsTimeZone object
        $timezone = new GoogleMapsTimeZone(trim($_POST['latitude']), trim($_POST['longitude']), GoogleMapsTimeZone::FORMAT_JSON);

        // Set Google API key
        $timezone->setApiKey(YOUR_API_KEY);

        $timezone_data = $timezone->queryTimeZone(); 
        if($timezone_data[status] == 'OK') {
            $timezoneid = $timezone_data[timeZoneId];
            $timezonename = $timezone_data[timeZoneName];
            $location .= '<br/>TimeZone: '.$timezoneid;
            $location .= '<br/>TimeZone Name: '.$timezonename;
        }
        echo $location; 
    }
?>




Related Article

Get current visitor's location using PHP
Complete HTML Form Validation in PHP
Simple star rating system using PHP, jQuery and Ajax
jQuery File upload progress bar with file size validation
JavaScript display PDF in the browser using Ajax call
jQuery loop over JSON result after AJAX Success




Read more articles


General Knowledge



Learn Popular Language