MapSnippets logo MapSnippets logo

Geofencing with OpenLayers

OpenLayers

Check whether a clicked point lies inside a geofence in OpenLayers by testing an ol.geom.Polygon boundary with intersectsCoordinate().

progress_activity Loading map...
var fenceCoords = [[13.38, 52.53], [13.43, 52.53], [13.43, 52.51], [13.38, 52.51], [13.38, 52.53]];
var fenceFeature = new ol.Feature({
  geometry: new ol.geom.Polygon([fenceCoords.map(function(c) { return ol.proj.fromLonLat(c); })])
});
var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({ features: [fenceFeature] }),
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({ color: '#e63946', width: 2 }),
    fill: new ol.style.Fill({ color: 'rgba(230,57,70,0.15)' })
  })
});
var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', attributions: '&copy; <a href="https://www.maptiler.com/copyright/">MapTiler</a>' }) }),
    vectorLayer
  ],
  view: new ol.View({ center: ol.proj.fromLonLat([13.405, 52.52]), zoom: 13 })
});
map.on('click', function(evt) {
  var inside = fenceFeature.getGeometry().intersectsCoordinate(evt.coordinate);
  var info = document.getElementById('info');
  info.textContent = inside ? 'Inside zone' : 'Outside zone';
  info.style.color = inside ? '#4CAF50' : '#e63946';
});

How to check if a point is inside a polygon in OpenLayers

OpenLayers renders the geofence as a polygon feature in a vector layer with a semi-transparent fill and a colored border. The polygon coordinates are transformed from [lng, lat] to the map’s EPSG:3857 projection using ol.proj.fromLonLat().

When the user clicks the map, the built-in intersectsCoordinate() method on the polygon geometry checks whether the click coordinate falls inside the fence. This is simpler than implementing ray-casting manually, because OpenLayers handles the math internally. The result is displayed in an info box overlaying the map.

Key APIs

API Description Docs
ol.geom.Polygon Polygon geometry openlayers.org
.intersectsCoordinate() Test if coordinate is inside geometry openlayers.org
map.on('click') Map click event openlayers.org

FAQ

Can I use GeoJSON to define the fence?

Yes. Load GeoJSON with ol.format.GeoJSON and its readFeatures() method. Make sure to set featureProjection: 'EPSG:3857' to transform coordinates automatically.

How do I check the user’s live GPS position?

Use navigator.geolocation.watchPosition(), transform the coordinates with ol.proj.fromLonLat(), and test against the polygon with intersectsCoordinate().

Does intersectsCoordinate work with complex polygons?

Yes. It handles concave polygons and polygons with holes correctly.

Common mistakes

  • Forgetting ol.proj.fromLonLat() when creating the polygon. The coordinates must be in the map projection (EPSG:3857).
  • Testing a [lng, lat] coordinate against a projected polygon. The click evt.coordinate is already in EPSG:3857, so it works directly.
  • Using containsCoordinate() from ol.extent instead, which checks the bounding box rather than the actual polygon shape

Build maps using OpenLayers with AI

Generate code like this geofencing with openlayers example using the OpenLayers skill in your IDE.