2013-03-01 96 views
3

所以我已经做了一些四处寻找,找不到任何能够真正回答我想要做的事情,因此我发布了!HTML5地理位置中经度和纬度的半径

我的总体目标主要是让页面读取用户位置,然后根据它们的位置运行代码。具体来说,我有一个Facebook检查脚本,将允许用户检查他们是否在特定的位置。

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

有没有人有任何想法?

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

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!');}; 
    } 
+1

顺便说一句,在倒数第二行代码中的同时设置lat和长为0,我怀疑这是你的意思做的: '如果(LAT = 0 &&长= 0){警报( '!它的工作原理');};' 也许应该 '如果(LAT = = 0 && long == 0){alert('It works!');};' – 2013-03-01 23:08:24

+0

好抓!我没有看到这个。我已经从实际坐标编辑为0,所以万一人们认为我很奇怪指向0/0,我不知道。 :p – Purify 2013-03-01 23:14:25

回答

5

我会做的是建立在使用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 
    } 
}