Skip to content

Ray casting, or how a phone knows it is in danger

Written byZaki Hattaon

A hand holding a smartphone with a gradient screen

A simple point in polygon test sits at the heart of Padang Rescue. Here is how it works, in plain terms.

Before the app can guide anyone to safety, it has to answer one question: is this person inside a hazard zone right now? Hazard zones are drawn as polygons on the map, and the user's location is a single point. Ray casting is the classic way to test whether that point is inside.

The idea

Imagine drawing a straight line from the user's position out to the edge of the map. Count how many times that line crosses the border of the polygon. An odd number means the point is inside. An even number means it is outside.

const isInside = (point: [number, number], polygon: [number, number][]) => {
    const [x, y] = point
    let inside = false

    for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
        const [xi, yi] = polygon[i]
        const [xj, yj] = polygon[j]
        const crosses = (yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi

        if (crosses) inside = !inside
    }

    return inside
}

Why it fits

It is fast, it needs no external service and it works offline, which matters when networks are failing. In Padang Rescue it runs every time the location updates, so the warning on screen always matches where the person is standing.