3 min read
Geofence validation on Google Maps JS API

Very early career, judge me less for this one.

**`Published: Feb 2019

Note: This post reflects my 2019 exploration of geofence validation. Today, libraries like Turf.js or GEOS handle these cases more efficiently.

Suppose you gotta setup drawing and saving of geofences on your website with Google Maps API. In my case, this was for fleet management, where vehicle owners wanted notifications for vehicles moving inside or outside a geofence drawn on the web app.

You say, hey that shouldn’t take much time. Boy oh boy are you wrong.

Suppose that there are just two types of shapes you have to handle, polygon and circle geofences.

You have to handle the following cases,

  1. Polygon drawn must not be self intersecting. There is something called Bentley–Ottmann algorithm to check if a polygon is self intersecting, it is hard to implement and should only be used if the number of points in the polygon is very large. Otherwise you can just check if any two set of lines in a polygon are intersecting. Run it in a loop in such a way that each line segment is checked with every other line segment in the polygon exactly once.
    Ref : https://math.stackexchange.com/a/80806
    Further reading : http://geomalgorithms.com/algorithms.html
  2. Polygon/Circle drawn must not intersect with any other geofences.
    1. New Polygon
      1. Must not intersect with another polygon. Loop through all the points in new polygon, check if this point falls inside the stored polygons.
      2. Must not intersect with another circle. Find the distance of each point in new polygon from the centre of the older circle. If the distance is lesser than the radius, we have an intersection.
    2. New Circle
      1. Must not intersect with another circle. Distance between the two circle’s centre must be greater than the sum of the two respective radii.
      2. Must not intersect with another polygon. Following the same method as mentioned before in this article for polygon-circle intersection.
  3. A polygon can intersect with another geofence even when no vertex of it is contained inside the other geofence. This is not really a special case, just another normal intersection case to handle in validation. In our fleet management use case, I was more concerned with practical containment checks for notification boundaries than exact geometric purity, so the only way I’d thought of at the time to manually validate this was to split the edges of the polygon and check for each point whether it falls inside any other geofence. The splitting distance becomes the tolerance for how much intersection is allowed. If you set the splitting distance too low, your frontend might hang doing this validation.

Now you can go ahead store this as GeoJSON object in whatever database you’re using.

If you’ve got a better way to handle the 3rd case, ping me.