iOS WebApp's don'不允许定位服务

iOS WebApp's don't allow location services?

本文关键字:定位 服务 不允许 don iOS WebApp      更新时间:2023-09-26

我有下面的JS,它可以获取用户的当前位置并显示他们的邮政编码。。。

(function ($, geolocation) {
    if (geolocation) {
        geolocation.getCurrentPosition(function (position) {
            $.getJSON(
                "http://ws.geonames.org/findNearestAddressJSON?callback=?",
                {
                    lat : position.coords.latitude,
                    lng : position.coords.longitude
                },
                function (data) {
                    $(function () {
                        $('#zip').text(data.address.postalcode);
                    });
                }
            );
        });
    }
}(jQuery, navigator.geolocation));

请帮助CodeReview,因为我的原始代码非常糟糕,https://codereview.stackexchange.com/questions/13481/to-use-or-not-to-use-public-variables-in-javascript/13483#comment21844_13483

HTML:

<div id="zip"></div>

然后在分区中显示邮政编码

这在移动Safari和桌面Safari中都很好,但一旦我添加了apple-mobile-web-app-capable元标记,代码就会中断。

在每一步之后,我都会将代码日志记录到控制台,并且在常规Safari和Mobile Safari中运行顺利。不过,当我把它添加到主屏幕上(头上有meta标签)时,该应用程序甚至不会运行JS代码。它也不需要登录控制台,这让我怀疑WebApps中是否允许定位服务。

如果在从主屏幕运行时重新加载页面,也会出现此问题。

有办法解决这个问题吗?这是常见问题吗?

是的,iOS web应用程序使用apple-mobile-web-app-capable元标记,允许通过navigator.geolocation提供定位服务。你没有错误回调,这可能会给你一个问题的提示。发布HTML以进行进一步分析。

试着把这个放在一个页面上(设置了apple-mobile-web-app-capable):

navigator.geolocation.getCurrentPosition( function ( position ) {
    alert( 'yay!' );    
},
function ( error ) {
    alert( 'boo! error: ' + error.message );
} );

根据你的评论,这是有效的,所以这不是定位服务。试着改变最后一行括号的顺序。

} )( jQuery, window.navigator.geolocation );

此外,这看起来有点奇怪,因为对.text()的调用会立即发生,而不是在.getJSON()完成时:

function (data) {
    $(function () {
        $('#zip').text(data.address.postalcode);
    });
}

尝试:

function (data) {
    $('#zip').text(data.address.postalcode);
}

所以你的最终代码应该是这样的:

( function ( $, geolocation ) {
    if (geolocation) {
        geolocation.getCurrentPosition( function ( position ) {
            $.getJSON(
                "http://ws.geonames.org/findNearestAddressJSON?callback=?",
                {
                    lat : position.coords.latitude,
                    lng : position.coords.longitude
                },
                function (data) {
                    $('#zip').text(data.address.postalcode);
                }
            );
        });
    }
} )( jQuery, window.navigator.geolocation );

苹果有自己的方法来实现webApps的本地化。如果你在iOS开发者程序中,你绝对应该查看官方文档。

看看这个:http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/GettingGeographicalLocations/GettingGeographicalLocations.html#//apple_ref/doc/uid/TP40002051-CH5-SW2