spelle
spelle

Reputation: 41

How can I check if the current location is outside of a set radius?

I'm currently working on an app that triggers a notification when someone is within a square. The following defines the square:

var zonebounds = [[30,35], [40,45]];
var zone = L.rectangle(zonebounds, {color: "#ff7800", weight: 1, oppacity: .5});

I've made the following statement to check if someone is within the square.

if (posY > zonebounds[0][0] && posY < zonebounds[1][0] && posX > zonebounds[0][1] && posX < zonebounds[1][1] && zoneTimer == 0) {
    ons.notification.toast('Test', { timeout: 5000 });
    zoneTimer = 1;
} else if (posY >! zonebounds[0][0] && posY <! zonebounds[1][0] && posX >! zonebounds[0][1] && posX <! zonebounds[1][1] && zoneTimer == 1) {
    zoneTimer = 0;
}

I think >! sadly doesn't behave as I would like it to.

I've made the zoneTimer variable so that the notification doesn't repeat itself. Maybe there is an even better way to do this.

Update

I fixed it by using a combination of the two answers I got, here is the final result:

if(zoneBoundslatLng.contains(latLng)){
    if (inZone == 0) {
    inZone = 1;
    ons.notification.toast('Zone 1, klik voor informatie.', { timeout: 5000 });
    }
} else {
    inZone = 0;
}

Upvotes: 2

Views: 108

Answers (2)

Falke Design
Falke Design

Reputation: 11378

You can check with leaflet if point is in the rectangle.

var bounds = L.latLngBounds(zonebounds);


if(bounds.contains(latlng) ){
    console.log("notify");
}else{
    console.log("nothing");
}

If your point (posX and posY) are pixels you can use this to convert:

var point = L.point(posX ,posY); // x=0,y=0
var latlng = map.layerPointToLatLng(point);

Update ...

var bounds = L.latLngBounds(zonebounds);

if(bounds.contains(latlng) && zoneTimer == 0){
    zoneTimer = 1;
    ons.notification.toast('Test', { timeout: 5000 });
    console.log("notify");
}else{
    zoneTimer = 0;
    console.log("nothing");
}

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386868

You could take the reverse of >, <= for checking.

For the second check, you need an OR condition.

if (
    posY > zonebounds[0][0] && posY < zonebounds[1][0] &&
    posX > zonebounds[0][1] && posX < zonebounds[1][1] &&
    zoneTimer === 0
) {
    ons.notification.toast('Test', { timeout: 5000 });
    zoneTimer = 1;
} else if (
    (posY <= zonebounds[0][0] || posY >= zonebounds[1][0] || 
    posX <= zonebounds[0][1] || posX >= zonebounds[1][1]) &&
    zoneTimer === 1
) {
    zoneTimer = 0;
}

A shorter check.

if (posY > zonebounds[0][0] && posY < zonebounds[1][0] && posX > zonebounds[0][1] && posX < zonebounds[1][1]) {
    if (zoneTimer === 0) {
        ons.notification.toast('Test', { timeout: 5000 });
        zoneTimer = 1;
    }
} else {
    if (zoneTimer === 1) {
        zoneTimer = 0;
    }
}

Upvotes: 2

Related Questions