How to Integrate HTML5 Geolocation API to Obtain Visitor Location in PHP?

html5-geolocation-api

If you are seeking to obtain a visitor’s PHP geolocation example, this tutorial is for you. Here, we have laid out the step by step process of integrating geolocation in your PHP website. So, let’s get started.

Introduction

Today, we’re all surrounded by smartphones with which our lives cannot continue without instant to web and apps for each need. Smartphones have evolved to a great extent in just three years, and now they provide a wide range of features that make our lives far easier. And for the location-challenged people, Geolocation API is one of the most useful additions. Many businesses today provide services based on location and therefore, it’s necessary to integrate this HTML5 Geolocation API in a PHP web service site.

Moreover, smartphones today, both Android and iPhone devices have been fitted with GPS to provide geographical location data, and in this PHP web development tutorial, we will discuss the capabilities of Geolocation navigator API of HTML5.

Steps to Integrate HTML5 Geolocation API

To obtain visitor location, we’ll need the following.

  1. CODE
  2. PHP

First, we’ll start with the code. Here’s the Code structure we’ll follow.

  1. Index.html
  2. GetLocation.php

Now create a new file with index.html to display the output.

NOTE: Define your browser version with a name for Geolocation navigator API functionality support.

Chrome

Version 5.0 to 49 support with HTTP protocol.

Version greater than 50 support only with https protocol.

Internet Explorer

Support version greater than 9.0

Mozilla Firefox

Support version greater than 3.5

Safari

Support version greater than 5.0

Operamini

Support version greater than 16.0

All these browser are available in the market.

Start Code Integration

  • HTML
<!DOCTYPE html> 
<html lang="en-US"> 
<head> 
<title>SPACE-O :: Get Visitor Location using HTML5</title> 

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

<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> 

<style type="text/css"> 

p{ border: 2px dashed #009755; width: auto; padding: 10px; font-size: 18px; border-radius: 5px; color: #FF7361;} 

    span.label{ font-weight: bold; color: #000;} 

</style> 

</head> 

<body> 

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

</body> 

</html>

NOTE:

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

This code is used for the HTML Geolocation API function. When you need to get Geolocation information, you must use jquery.min.js

The following code is to validate whether the Geolocation API supported or not.

<script> 

$(document).ready(function(){ 

    if (navigator.geolocation) { 

        navigator.geolocation.getCurrentPosition(showLocation); 

    } else { 

        $('#location').html('Geolocation is not supported by this browser.'); 

    } 

}); 

If you get the Geolocation details of visitors, then call the below function to get the format address.

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> 
  • GetLocation.php
<?php 

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($status=="OK"){ 

        //Get address from json data 

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

    }else{ 

        $location =  ''; 

    } 

    //Print address 

    echo $location; 

} 

?>

And Done!

Want to Create a Web Application?

Validate your app idea and get a free quote.

FAQs

What is position coords latitude and position coords longitude?

Both position coords latitude and position coords longitude are functions that can be used to fetch and display a location in Googleapis com maps api. (Here’s an example where a user’s latitude and longitude are fetched)

What is navigator geolocation?

The navigator geolocation is a read-only property that returns a Geolocation object that gives Web content access to the location of the device. This allows a site to a web app to deliver personalized UX based on the user’s location. By using navigator geolocation getcurrentposition, you can get a user’s exact location which can be displayed on Google map.

What can I do by obtaining a user’s geolocation?

Based on a user’s geolocation, you can customize the results they see – and show them more relevant items.

Conclusion

Now that you know how to use PHP geolocation API, it’s time you take the action. And if still confused, whether to use internal geolocation service or external. The answer is simple. Use external geolocation service whenever the option is available. External service provides geolocation of visitors by using large geolocation databases, meaning they’ll do a far better job. And in case you need help, hire PHP developer and layout your plan and integrate Geolocation API as soon as possible.

Grab a free copy of HTML5 Geolocation Demo from Github.

You may also like,

This page was last edited on January 11th, 2021, at 5:25.

Author Bio

Jigar Mistry

Jigar Mistry

Designation: Vice President (Technologies)

Jigar Mistry is Vice President (Technologies) at Space-O Technologies. He has 14+ years of experience in the web and mobile app development industry. He has expertise in different mobile app categories like health and fitness, eCommerce, and on-demand.

 
 

Want to Develop Location-Based Web Apps? Contact Us Now

Get your free consultation now

Leave a Reply

Your email address will not be published. Required fields are marked *