[聚合文章] iOS WebView 加载的时候定位

JavaScript 2018-01-17 31 阅读

项目中要添加外卖,H5做的,要获取定位权限。

当我们使用H5与Native进行混合开发时候,如果需要web界面在加载时候获取手机定位权限,之前的项目用的是加载web之前把所需坐标拼接到网址内,但是这次的页面是vue写的动态web,所以就不是很合适了,那就直接把这个动作交给H5去处理得了。

项目配置

iOS8.0之后,app内需要定位权限的话,则需要在 info.plist 中添加一行配置,如下:

或者右键info.plist->open as source code,添加如下代码

<key>NSLocationWhenInUseUsageDescription</key>
<string>定位1</string>

注意点

这里需要注意一下,上方必须添加当应用启动期间获取定位权限的key,即NSLocationWhenInUseUsageDescription,如果info.plist中只添加了 NSLocationAlwaysUsageDescription 这个始终定位的key,则H5的geoLocation无法向手机请求定位权限。

然后就会弹出下面的界面

web案例代码

<html>
    <head>
        <script>
            var getLocation = function() {
                if (navigator.geolocation){
                    navigator.geolocation.getCurrentPosition(displayPosition, locationError);
                } else {
                    alert('浏览器不支持地理定位。');
                }
            }
            var displayPosition = function(pos) {
                alert('latitude:'+ pos.coords.latitude+',longitude'+ pos.coords.longitude);
                document.getElementById("label").innerHTML = 'latitude:'+ pos.coords.latitude+',longitude:'+ pos.coords.longitude;
                var properties = ['longitude', 'latitude', 'altitude', 'accuracy', 'altitudeAccuracy', 'heading', 'speed'];
                for (var i = 0, len = properties.length; i < len; i++) {
                    var value = pos.coords[properties[i]];
                    document.getElementById(properties[i]).innerHTML = value;
                }
                document.getElementById('timestamp').innerHTML = pos.timestamp;
            }
            var locationError = function(error){
                switch(error.code) {
                    case error.TIMEOUT:
                    showError('A timeout occured! Please try again!');
                    break;
                    case error.POSITION_UNAVAILABLE:
                    showError('We can\'t detect your location. Sorry!');
                    break;
                    case error.PERMISSION_DENIED:
                    showError('Please allow geolocation access for this to work.');
                    break;
                    case error.UNKNOWN_ERROR:
                    showError('An unknown error occured!');
                    break;
                }
            }
            var showError = function(error){
                alert(error);
            }
        </script>
    </head>
    <body onload="getLocation()">
        <span id="label">1111111</span>
    </body>
</html>

最终效果

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。