繁体   English   中英

使用PHP检测HTML5地理位置支持

[英]Detect HTML5 Geolocation Support Using PHP

我需要使用PHP检测HTML5 Geolocation支持,以便我可以使用IP地址加载支持Geolocation的备份JavaScript。

如何使用或不使用PHP。

您是否考虑过使用Modernizr来检测HTML5支持? 这不是PHP特定的,因为它是在JavaScript中完成的,但您可以使用此代码段来加载备份文件:

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);
}

(基于http://www.modernizr.com/docs/#geolocation

您可以使用canisuse.js脚本来检测您的浏览器是否支持地理定位

caniuse.geolocation()

您可以使用javascript检查地理位置支持:

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

我把好的Dive中的函数带到了HTML 5中

那么检测Geolocation的唯一方法是使用导航器,并使用如下:

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

所以我个人会做的是创建一个Ajax请求到服务器并执行重定向,如下所示:

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.
         */
    });
}

在服务器端你会做这样的事情:

<?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;
}
?>

现在当javascript重定向你时,在你的索引中你可以在输出你的html之前查看是否存在,那么如果支持GEO,你就会知道服务器端!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM