简体   繁体   English

getCurrentPosition在Firefox中仅触发一次

[英]getCurrentPosition only fires once in Firefox

Take a look at this code: 看一下这段代码:

navigator.geolocation.getCurrentPosition(function(){
    console.log("a");
});
navigator.geolocation.getCurrentPosition(function(){
    console.log("b");
});

https://jsfiddle.net/DerekL/sxb3j2bv/ https://jsfiddle.net/DerekL/sxb3j2bv/

After the permission is granted by the user, I would expect the console to have logged 用户授予该权限后,我希望控制台已记录

> "a"
> "b"

and indeed this is what happened in Chrome. 实际上,这就是Chrome中发生的情况。 However on Firefox, for some reason it only fires once and only logs "b" : 但是在Firefox上,由于某种原因,它只会触发一次,并且只会记录"b"

> "b"

What can I do about it? 我该怎么办? Is that a bug? 那是个错误吗?

I believe this is happening because the second call executes before the user has accepted the location permission for the first. 我相信这是因为第二个调用在用户接受第一个调用的位置许可之前执行。

However, you probably want to look at 但是,您可能想看看

navigator.geolocation.watchPosition navigator.geolocation.watchPosition

rather than making multiple requests to get the position. 而不是多次要求获得职位。

I solved it by reusing the previous request's promise: 我通过重用上一个请求的承诺解决了它:

// Note that this is using AngularJS
.service("demo_geolocation_service", function($q){
    var ongoingRequest = false; // This is to deal with strange Firefox behavior
                                //  where .getCurrentPosition only fires callback once
                                //  even when called multiple times

    return function(){
        var deferred = $q.defer();

        if(!ongoingRequest){
            // store promise
            ongoingRequest = deferred.promise;
            navigator.geolocation.getCurrentPosition(function(pos){
                deferred.resolve({latitude: pos.coords.latitude, longitude: pos.coords.longitude});
                ongoingRequest = undefined;
            }, function(){
                deferred.reject();
                ongoingRequest = undefined;
            });
        }else{
            // reuse previous promise
            ongoingRequest.then(function(latlng){
                deferred.resolve(latlng);
            }, function(){
                deferred.reject();
            });
        }

        return deferred.promise;
    };
})

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

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