我想根据距离显示一个 div。为此,我正在获取用户的位置和 div 应该出现的位置的坐标,并且我正在成功地实现这一点。我现在的问题是,我希望在不同的地方可以使用它,所以我需要找到一种方法来循环并不断检查这个人的位置,看看它是否接近我的坐标距离。
-- 获取人的位置
if (navigator.geolocation){
navigator.geolocation.watchPosition(showPosition)
}
-- 工作 div 出现的功能
function showPosition(position){
let locationLatitude = []
let locationsLongitude = []
//AJAX CALL TO GET THE POSITION OF THE PLACES AND PUSHING THEM TO THE ARRAYS
let success = function(res){
let locations = res.locations
for (var i=0; i<locations.length; i++){
locationLatitude.push(locations[i]['place_latitude'])
locationsLongitude.push(locations[i]['place_longitude'])
}
}
$.ajax({
type: 'GET',
url: '/api/locations',
crossDomain: true,
dataType: 'json',
async: false,
success : success,
});
// LOOP TO GET ALL COORDIANTES FROM PLACES (LAT,LONG)
var locationLatitudeLength = locationLatitude.length
var locationsLongitudeLength = locationsLongitude.length
let startPosLat
let startPosLong
for(var i=0; i<locationLatitudeLength; i++){
for(var j=0; j<locationsLongitudeLength; j++){
startPosLat = locationLatitude[i]
startPosLong = locationsLongitude[j]
userlocationLatitude = position.coords.latitude
userlocationLongitude = position.coords.longitude
//PASS VALUES OF COORDINATES TO THE FUNCTION
let distance = calculateDistance(startPosLat, startPosLong, userlocationLatitude, userlocationLongitude)
}
}
if(distance < .05){
$('.div-image').attr('src', 'pic2.jpg')
}else if(distance > .05){
$('.div-image').attr('src', 'pic.jpg')
}
//function to calculate the distance between two points of coordinates
function calculateDistance(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
问题在于它无法识别来自循环的坐标。
任何人都有关于如何使函数为循环上的每个坐标运行以检查我是否在那里的建议。