向navigator.geolocation.getCurrentPosition添加多个侦听器

时间:2018-02-09 10:40:52

标签: javascript html geolocation

我正在为位置更新添加三个侦听器。

<!DOCTYPE html>
    <html>
    <body>
    
    <p>Click the button to get your coordinates.</p>
    
    <button onclick="getLocation()">Try It</button>
    
    <p id="demo1"></p>
    <p id="demo2"></p>
    <p id="demo3"></p>
    
    <script>
    var x = document.getElementById("demo1");
    var y = document.getElementById("demo2");
    var z = document.getElementById("demo3");
    
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition1);
            navigator.geolocation.getCurrentPosition(showPosition2);
            navigator.geolocation.getCurrentPosition(showPosition3);
        } else { 
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }
    
    function showPosition1(position) {
        alert("showPosition1");
        x.innerHTML = "Latitude: " + position.coords.latitude +  "<br>Longitude: " + position.coords.longitude;
    }
    
    function showPosition2(position) {
        alert("showPosition2");
        y.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
    }
    
    function showPosition3(position) {
        alert("showPosition3");
        z.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
    }
    </script>
    
    </body>
    </html>

对于Safari和Chrome,会调用所有三种方法。在Firefox的情况下,只调用最后一个侦听器方法。

那么位置检测功能的默认实现是什么。是否有解决方法确保在Firefox上调用所有回调方法。

2 个答案:

答案 0 :(得分:2)

Firefox在地理位置中实施错误的历史很长。

你现在可以做的就是用猴子修补getCurrentPosition

来解决这个问题
var getCurrentPosOrg = navigator.geolocation.getCurrentPosition;

function getCurrentPositionMod () {
    const listners = [];
    function runAllListners(...args) {
        listners.forEach(curr => curr(...args));
    }
    return (cb) => {
        listners.push(cb);
        getCurrentPosOrg(runAllListners);
    }
}

navigator.geolocation.getCurrentPosition = getCurrentPositionMod();

使用此补丁,您只需使用getCurrentPosition,就不必再担心Firefox了。如果您需要删除侦听器,您也可以扩展此方法。

您的代码片段现在看起来就像这样。

<!DOCTYPE html>
<html>

<body>

  <p>Click the button to get your coordinates.</p>

  <button onclick="getLocation()">Try It</button>

  <p id="demo1"></p>
  <p id="demo2"></p>
  <p id="demo3"></p>

  <script>
    if (navigator.geoloaction) {
      var getCurrentPosOrg = navigator.geolocation.getCurrentPosition;

      function getCurrentPositionMod() {
        const listners = [];

        function runAllListners(...args) {
          listners.forEach(curr => curr(...args));
        }
        return (cb) => {
          listners.push(cb);
          getCurrentPosOrg(runAllListners);
        }
      }

      navigator.geolocation.getCurrentPosition = getCurrentPositionMod();
    }
    var x = document.getElementById("demo1");
    var y = document.getElementById("demo2");
    var z = document.getElementById("demo3");

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition1);
        navigator.geolocation.getCurrentPosition(showPosition2);
        navigator.geolocation.getCurrentPosition(showPosition3);
      } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
    }

    function showPosition1(position) {
      alert("showPosition1");
      x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
    }

    function showPosition2(position) {
      alert("showPosition2");
      y.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
    }

    function showPosition3(position) {
      alert("showPosition3");
      z.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
    }
  </script>

</body>

</html>

答案 1 :(得分:0)

在地理定位API上使用eventWatcher尝试。 这是一个完整的HTML和JavaScript。

<!DOCTYPE html>
<html>
    <head>
        <title>DEMO</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <p>Click the button to get your coordinates.</p>

        <button onclick="startGeolocation() ">Start Geolocation</button>
        <button onclick="stopLocation()">Stop Geolocation</button>

        <script>
            var observerID = -1;

            function startGeolocation() {
                //INITIALIZE EVENT WAHTCER POSITIONS
                if (navigator.geolocation) {
                    observerID = navigator.geolocation.watchPosition(onSuccess, onError, {
                        maximunAge: 60000,
                        enableHighAccuracy: true,
                        timeout: 20000
                    });

                }

            }

            function stopGeolocation() {

                if (observerID !== -1) {
                    navigator.geolocation.clearWatch(observerID);
                    observerID = -1;

                }
            }

            function onSuccess(pos) {
                //THIS EVENT FIRE WHEN POSITIONS HAVE DATA.
                var lat = pos.coords.latitude;
                var lng = pos.coords.longitude;
                var accuracy = pos.coords.accuracy;
                var altitude = pos.coords.altitude;
                var altitudeAccuraccy = pos.coords.altitudeAccuracy;
                var heading = pos.coords.heading;
                var spped = pos.coords.speed;
                var timeSpan = pos.coords.timestamp;
                //ADD YOU CODE HERE...
            }

            function onError(error) {
                switch (error.code) {
                    case error.PERMISSION_DENIED:

                        alert("USER NOT ACCEPTED PERMISSION.");
                        break;
                    case error.POSITION_UNAVAILABLE:
                        alert("POSITION NOT AVAIBLE.");
                        break;
                    case error.TIMEOUT:

                        alert(true, "TIME OUT.");
                        break;
                    case error.UNKNOWN_ERROR:
                        alert(true, "OTHER ERROR.");
                        break;
                }

            }

        </script>
    </body>

</html>