MapSnippets logoMapSnippets logo

Geolocation with OpenLayers

OpenLayers

Track and display the user's current position as a point feature on an OpenLayers map using the browser Geolocation API.

progress_activityLoading map...
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>' }) })
  ],
  view: new ol.View({ center: ol.proj.fromLonLat([0, 0]), zoom: 2 })
});
var positionFeature = new ol.Feature();
positionFeature.setStyle(new ol.style.Style({
  image: new ol.style.Circle({ radius: 8, fill: new ol.style.Fill({ color: '#2196F3' }), stroke: new ol.style.Stroke({ color: '#fff', width: 2 }) })
}));
var accuracyFeature = new ol.Feature();
var locationLayer = new ol.layer.Vector({ source: new ol.source.Vector({ features: [accuracyFeature, positionFeature] }) });
map.addLayer(locationLayer);
var geolocation = new ol.Geolocation({
  trackingOptions: { enableHighAccuracy: true },
  projection: map.getView().getProjection(),
  tracking: true
});
geolocation.on('change:position', function() {
  var coords = geolocation.getPosition();
  positionFeature.setGeometry(coords ? new ol.geom.Point(coords) : null);
  map.getView().animate({ center: coords, zoom: 15 });
});
geolocation.on('change:accuracyGeometry', function() {
  accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
});

How it works

OpenLayers has a built-in ol.Geolocation class that wraps the browser’s Geolocation API. Setting tracking: true starts watching the user’s position.

Two features visualize the location: a circle for the position and a polygon for the accuracy radius. The change:position event fires when new coordinates are available, and the map animates to center on the user.

The projection option ensures coordinates are returned in the map’s projection (EPSG:3857), so no manual conversion is needed.

Key APIs

API Description Docs
ol.Geolocation Browser geolocation wrapper openlayers.org
getPosition() Get current position in map projection openlayers.org
getAccuracyGeometry() Get accuracy circle as polygon openlayers.org

FAQ

What happens if the user denies location permission?

The ol.Geolocation object fires an error event. Listen for it with geolocation.on('error', handler) and show a fallback message.

Does this work on mobile devices?

Yes. Mobile browsers provide GPS-based positions with higher accuracy. Set enableHighAccuracy: true to prefer GPS over network-based positioning.

Common mistakes

  • Forgetting to set projection on the Geolocation instance: coordinates will be in WGS84, not the map’s projection
  • Not handling the error event: the code silently fails if permission is denied
  • Animating on every position update in tracking mode: this can be disorienting. Consider only centering on the first fix
auto_awesome

Build maps using OpenLayers with AI

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