取消 HTML5 中正在進行的 watchPosition 呼叫


clearWatch 方法會取消正在進行的 watchPosition 呼叫。當取消後,watchPosition 呼叫將停止檢索裝置當前地理位置的更新資訊。

<!DOCTYPE HTML>
<html>
   <head>
      <script>
         var watchID;
         var geoLoc;

         function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            alert("Latitude : " + latitude + " Longitude: " + longitude);
         }

         function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            }
            else if( err.code == 2) {
               alert("Error: Position is unavailable!");
            }
         }

         function getLocationUpdate(){
            if(navigator.geolocation){
               // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               geoLoc = navigator.geolocation;
               watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
            }
            else{
               alert("Sorry, browser does not support geolocation!");
            }
         }

         function stopWatch(){
            geoLoc.clearWatch(watchID);
         }
      </script>
   </head>

   <body>
      <form>
         <input type = "button" onclick = "getLocationUpdate();" value = "Watch Update"/>
         <input type = "button" onclick = "stopWatch();" value = "Stop Watch"/>
      </form>
   </body>
</html>

更新於: 2020 年 1 月 28 日

208 次瀏覽

開啟職業發展生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.