javascript - 如何为数组上的每个元素运行函数
问题描述
我想根据距离显示一个 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;
}
}
问题在于它无法识别来自循环的坐标。
任何人都有关于如何使函数为循环上的每个坐标运行以检查我是否在那里的建议。
解决方案
似乎通过坐标的双循环不会等待来自 ajax 的响应(我假设在处理之前需要所有坐标)。由于 ajax 调用是异步的,因此在服务器响应之前不会填充位置;但是,通过位置数组的循环将在向服务器发出初始请求后立即开始执行,最重要的是,在填充位置之前。
尝试将您的大部分功能转移到成功功能中。
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'])
}
// 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')
}
}
$.ajax({
type: 'GET',
url: '/api/locations',
crossDomain: true,
dataType: 'json',
async: false,
success : success,
});
//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;
}
}```
推荐阅读
- python - 如何在带有 OR 条件的 re.search 中使用多个字符串?
- rust - 如何通过期货通道将异步消息发送到接收器?
- php - 将一串逗号分隔值转换为真/假数组
- react-native - React Native:在本地服务器上使用 axios 时出现网络错误
- javascript - 在 JSON 请求中发送 csrf_token(无 ajax)
- mongodb - 查找 mongo 文档 - 具有嵌套字符串数组的文档数组
- entity-framework - Linq 查询(无法翻译)
- c++ - 使用结构和指针的分段错误(核心转储)
- c++ - 如果我想在 C++ 中输入但整数很长(例如 1000101010101001),我该怎么办?
- openshift - 从 Mac 登录 Openshift oc 失败