【问题标题】:Mobile webpage using location services - give user native link to setting when location services are off使用位置服务的移动网页 - 在位置服务关闭时为用户提供设置的本地链接
【发布时间】:2014-10-07 20:35:56
【问题描述】:

我们有一些基于位置的搜索,这些搜索利用了用户的纬度和经度。首先,它尝试根据 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 上的设置的链接,所以他们可以轻松开启定位服务。

我认为这对于 Android 和 iphone 可能是不同的代码,我不知道从哪里开始获取他们设置的链接。

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

【问题讨论】:

    标签: javascript php android iphone


    【解决方案1】:

    navigator.geolocation 对象是标准化的,present on all recent browsers。因此,您可以简单地检查它的存在。

    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

    【讨论】:

      猜你喜欢
      • 2015-10-04
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      • 1970-01-01
      相关资源
      最近更新 更多