Aayush
Aayush

Reputation: 3098

Detect HTML5 Geolocation Support Using PHP

I need to detect HTML5 Geolocation support using PHP so that I can load a backup JavaScript that supports Geolocation using IP Address.

How to do this with or without PHP.

Upvotes: 4

Views: 7986

Answers (5)

Beka Tomashvili
Beka Tomashvili

Reputation: 2301

You can use canisuse.js script to detect if your browsers supports geolocation or not

caniuse.geolocation()

Upvotes: 0

Davide Gualano
Davide Gualano

Reputation: 13003

You can check Geolocation support using javascript:

function supports_geolocation() { 
     return !!navigator.geolocation; 
}

I've taken the function from the nice Dive into HTML 5.

Upvotes: 0

RobertPitt
RobertPitt

Reputation: 57268

Well the only way to detect Geolocation is with the navigator, and used like so:

if(navigator.geolocation)
{
     //Geo in Browser
}

So what I would personally do is create an Ajax request to server and do a redirect like so:

if(navigator.geolocation)
{
    navigator.geolocation.getCurrentPosition(function(position){
        /*
            * Send Position to server where you can store it in Session 
         */
        document.location = '/'; //Redirect and use the session data from above
    }, function(message){
        /*
            * Send false to the server, and then refresh to remove the js geo check.
         */
    });
}

on server side you would do something like so:

<?php /* session/geolocation.php */

//Require system files
include '../MasterBootloader.php';

/*
    * Session is already started in the above inclustion
*/

if(!isset($_SESSION['geo']['checked']) && is_agax_request())
{
    $_SESSION['geo'] = array();
    if(isset($_GET['postition']))
    {
        $_SESSION['geo']['supported'] = true;
        $_SESSION['geo']['location'] = json_decode($_REQUEST['geo_position']);
    }
    $_SESSION['geo']['checked'] = true;
}
?>

now when the javascript redirects you, in your index you can check to see if the exists before outputting your html, then you will know server side if GEO is supported!

Upvotes: 0

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

Have you considered using Modernizr to detect the HTML5 support? This isn't PHP specific since it's done in JavaScript but you can use this snippet to load your backup file:

if (Modernizr.geolocation){
   // Access using HTML5
   navigator.geolocation.getCurrentPosition(function(position) { ... });
}else{
   // Load backup file
   var script = document.createElement('script');
   script.src = '/path/to/your/script.js';
   script.type = 'text/javascript';
   var head = document.getElementsByTagName("head")[0];
   head.appendChild(script);
}

(Based on http://www.modernizr.com/docs/#geolocation)

Upvotes: 7

Related Questions