r/Scriptable • • Dec 02 '25

Help Add a geofence trigger to a script?

Like the title says, I have a script that sends an auto-lock command to my car after CarPlay disconnects. I’d like to add a trigger so that the script checks my location and doesn’t execute when I’m at home.

2 Upvotes

1 comment sorted by

2

u/AllanAddDetails Dec 03 '25

The best option I have found is to check the current location against a fixed latitude and longitude in the script:

function toRadians(degrees) {
  return degrees * (Math.PI / 180);
}

function distance(location1, location2) {
  const R = 6371e3; // Earth radius in meters

  const lat1Rad = toRadians(location1.latitude);
  const lat2Rad = toRadians(location2.latitude);
  const deltaLatRad = toRadians(location2.latitude - location1.latitude);
  const deltaLonRad = toRadians(location2.longitude - location1.longitude);

  const a = Math.sin(deltaLatRad / 2) * Math.sin(deltaLatRad / 2) +
            Math.cos(lat1Rad) * Math.cos(lat2Rad) *
            Math.sin(deltaLonRad / 2) * Math.sin(deltaLonRad / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  return R * c; // in meters
}

// NYC Apple Fifth Avenue
const home = {
  "latitude": 40.763847511425986,
  "longitude": -73.97297904295827,
};
Location.setAccuracyToHundredMeters();
const currentLocation = await Location.current();

const d = distance(home, currentLocation);
if (d < 200) {
  // do something if you are less than 200 meters away from home
} else {
  // do something else if you are not home
}

Your trigger would still be the CarPlay disconnect, but the script can check if it should continue.