所以我四处看了看,找不到任何能真正回答我想做的事情的东西,所以我发帖了!
我的总体目标基本上是让页面读取用户位置,然后根据用户所在位置运行代码。具体来说,我有一个 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!');};
}
最佳答案
我要做的是使用 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
}
}
关于javascript - HTML5地理定位中的经纬度半径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15168299/