5

所以我做了一些环顾四周,找不到任何真正回答我想要做的事情的东西,因此我发布了!

我的总体目标本质上是让页面读取用户位置,然后根据他们所在的位置运行代码。具体来说,我有一个 facebook 签入脚本,允许用户在特定位置签入。

问题是有问题的位置有点大,所以手动输入位置的坐标是行不通的。我现在坚持的是是否有可能告诉 JS 采用硬编码的位置的经度和纬度,但在坐标周围给出一个半径(比如说 200 米),所以当用户输入坐标的 200m 半径时代码激活。

有没有人有任何想法?

到目前为止,这是我的代码。

    jQuery(window).ready(function(){   
        initiate_geolocation();
    });  
    function initiate_geolocation() {  
        navigator.geolocation.getCurrentPosition(handle_geolocation_query,handle_errors);  
    }  
    function handle_errors(error)  
    {  
        switch(error.code)  
        {  
            case error.PERMISSION_DENIED: alert("user did not share geolocation data");  
            break;  
            case error.POSITION_UNAVAILABLE: alert("could not detect current position");  
            break;  
            case error.TIMEOUT: alert("retrieving position timed out");  
            break;  
            default: alert("unknown error");  
            break;  
        }  
    }  
     function handle_geolocation_query(position){  
         var lat = position.coords.latitude;
         var long = position.coords.longitude;

                      //these are for testing purposes
          alert('Your latitude is '+lat+' and longitude is '+long);
          if (lat == 0 && long == 0) {alert('It works!');};
    } 
4

1 回答 1

12

我要做的是使用 setInterval 创建一个轮询函数,每 1 到 10 秒执行一次,具体取决于什么对您的测试最有意义,并且只测试距离。这是一个测试两个经度/纬度之间距离的函数:

function CalculateDistance(lat1, long1, lat2, long2) {
    // Translate to a distance
    var distance =
      Math.sin(lat1 * Math.PI) * Math.sin(lat2 * Math.PI) +
      Math.cos(lat1 * Math.PI) * Math.cos(lat2 * Math.PI) * Math.cos(Math.abs(long1 - long2) * Math.PI);

    // Return the distance in miles
    //return Math.acos(distance) * 3958.754;

    // Return the distance in meters
    return Math.acos(distance) * 6370981.162;
} // CalculateDistance

您的区间函数看起来像:

// The target longitude and latitude
var targetlong = 23.456;
var targetlat = 21.098;

// Start an interval every 1s
var OurInterval = setInterval(OnInterval, 1000);

// Call this on an interval
function OnInterval() {
  // Get the coordinates they are at
  var lat = position.coords.latitude;
  var long = position.coords.longitude;
  var distance = CalculateDistance(targetlat, targetlong, lat, long);

  // Is it in the right distance? (200m)
  if (distance <= 200) {
    // Stop the interval
    stopInterval(OurInterval);

    // Do something here cause they reached their destination
  }
}
于 2013-03-01T23:18:14.603 回答