停止执行getCurrentPosition方法

Lai*_*ila 6 javascript jquery geolocation google-maps-api-3 jquery-mobile

我在Javascript中使用getCurrentPosition方法.我想实现一个按钮,在单击时停止执行方法"getCurrentPosition".我尝试使用throw/try/catch块,但它似乎不起作用:


    try {
        $('#cancel').on("click", function() { 
            $.mobile.loading('hide'); 
            throw "stop";
        });
        navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {enableHighAccuracy: true, timeout : 30000 }); 
    }
    catch ( er ) { alert(er); return false; }

有任何想法吗?它甚至可以在JS?我有一个想法,但我不知道是否可以使用JS方法触发超时,以便getCurrentPosition中断?

Gaj*_*res 11

解:

方法navigator.geolocation.getCurrentPosition是一个异步函数,所以不要指望像那样停止它.

您应该使用其他函数:navigator.geolocation.watchPosition.它的工作方式与getCurrentPosition相同,但在你的情况下使它有用的是另一个名为navigator.geolocation.clearWatch的函数,该函数用于停止watchPosition.

例:

geoLoc = navigator.geolocation;
watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
geoLoc.clearWatch(watchID);
Run Code Online (Sandbox Code Playgroud)