使用定位服务的移动网页-当定位服务关闭时,为用户提供设置的本地链接


Mobile webpage using location services - give user native link to setting when location services are off

我们有一些基于位置的搜索,利用用户的纬度和经度。首先,它试图将基于IP的lat/long作为回退,如下所示:

// get lat and long based on users ip address
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://freegeoip.net/json/" . $_SERVER['REMOTE_ADDR']);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$output = curl_exec($ch);
$location = json_decode($output);
curl_close($ch);
$ip_latitude = $location->latitude;
$ip_longitude = $location->longitude;

但由于在许多情况下这并不是非常准确,因此我们使用基于设备的用户地理编码,如下所示:

    function myfunction () {
    // check if geolocation is available
            x = navigator.geolocation;
            x.getCurrentPosition(success, failure);
    // if available, set variables in the form for lat/long and autofill the search box with 'current location'
            function success(position){
                document.getElementById('latitude').value = position.coords.latitude;
                document.getElementById('longitude').value = position.coords.longitude;
                document.getElementById('input-box-field1').value = 'Current Location';
            }
// if not available, then fall back to IP geocode for the form variables as well as give the user an alert that their location services aren't on.
            function failure()
            {
                document.getElementById('latitude').value = <?php echo $ip_latitude;;?>;
                document.getElementById('longitude').value = <?php echo $ip_longitude;?>;
                alert("Your location services are off.  Using an approximate location.");
                document.getElementById('input-box-field1').value = 'Current Location';
            }
    }

这一切都很好,然而,当用户的定位服务没有打开时,我希望警报是一个更原生的选项,也可以为用户提供一个指向他们在iphone或Android上的设置的链接,这样他们就可以轻松地打开定位服务。

我想这可能是andriod和iphone的不同代码,我不知道从哪里开始获取它们设置的链接。

提前感谢您在正确方向上提供的任何帮助。

navigator.geolocation对象是标准化的,并且出现在所有最新的浏览器上。因此,您可以简单地检查它的存在。

var showPos = function(position) { alert(position.coords); console.log(position.coords); }
if (navigator.geolocation)
 { navigator.geolocation.getCurrentPosition(showPos); }
else
  { alert("Noooo!"); }

请注意,getCurrentPosition是一个"异步"调用,即它不会立即返回结果,而是期望回调,一旦能够检索到位置,就会立即调用该回调。

w3scools有一个更复杂的错误处理示例:http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_geolocation_error