当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Update item from foreach every 10.5 seconds

问题描述:

So I have this code:

$.getJSON( "fetch-beacons.php", function( beacons ) {

beacons.forEach(function(beacon) {

if (beacon.uid != "<?php echo $uid ?>"){

var circle = new google.maps.Circle({

strokeColor: '#add8e6',

strokeOpacity: 0.8,

fillColor: '#add8e6',

fillOpacity: 0.35,

map: map,

center: new google.maps.LatLng(Number(beacon.lat), Number(beacon.lng)),

radius: Number(beacon.radius)

});

circle.addListener('click', function() {

post('claimcreds.php', {id: beacon.id, cid: <?php echo $uid ?>, uid: beacon.uid, lat: pos.lat, lng: pos.lng, claimattempt: "true"});

});

}

else {

var circle = new google.maps.Circle({

strokeColor: '#ffa500',

strokeOpacity: 0.8,

fillColor: '#ffa500',

fillOpacity: 0.35,

map: map,

center: new google.maps.LatLng(Number(beacon.lat), Number(beacon.lng)),

radius: Number(beacon.radius)

});

}

});

});

It's fetching details about some circles from a JSON document, and it works fine. The problem is, I want to check the circle position against another position (let's call it pos) every 10 seconds, to see whether pos is inside the circle.

As I understand it, the way to do this is google.maps.geometry.spherical.computeDistanceBetween(circle.center, pos); and then see if the radius is more or less than that, however I'm not sure how I'd do that every ten seconds, given that the circle variables aren't saved as they are looped through by the beacons.forEach statement.

Can anyone help? Sorry if what I'm asking isn't clear/if the code's a bit messy hehe :)

网友答案:

I think I would do something like this. Firstly define a global function like:

function checkDistance(circle) { 
    var distance = google.maps.geometry.spherical.computeDistanceBetween(circle.getCenter(), pos);

    if (distance > x) {
        alert('ok');
    }
}

It takes one parameter, circle. I'm assuming pos is a global variable it can access.

Then inside your forEach loop, after your if-else statement (assuming you want to apply it to both kinds of circle), call that function on a 10.5 second interval. It uses the circle variable you've just created as a parameter you pass to the function:

setInterval(checkDistance, 10500, circle);
分享给朋友:
您可能感兴趣的文章:
随机阅读: