MapSnippets logoMapSnippets logo

Polygon Features in OpenLayers

OpenLayers

Render a styled polygon area using a vector source with ol.geom.Polygon and custom fill/stroke styles.

progress_activityLoading map...
var polygon = new ol.Feature({
  geometry: new ol.geom.Polygon([[
    ol.proj.fromLonLat([2.33, 48.87]),
    ol.proj.fromLonLat([2.37, 48.87]),
    ol.proj.fromLonLat([2.37, 48.85]),
    ol.proj.fromLonLat([2.33, 48.85]),
    ol.proj.fromLonLat([2.33, 48.87])
  ]])
});
var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({ features: [polygon] }),
  style: new ol.style.Style({
    fill: new ol.style.Fill({ color: 'rgba(230, 57, 70, 0.3)' }),
    stroke: new ol.style.Stroke({ color: '#e63946', width: 2 })
  })
});
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([2.35, 48.86]), zoom: 14 })
});

How it works

An ol.geom.Polygon takes an array of linear rings. The first ring is the outer boundary. Each ring is an array of coordinates where the first and last point must be identical to close the polygon.

The style uses both ol.style.Fill for the interior color (with alpha transparency) and ol.style.Stroke for the border. This combination creates a visible filled area with a defined edge.

Key APIs

API Description Docs
ol.geom.Polygon Polygon geometry from coordinate rings openlayers.org
ol.style.Fill Fill style for polygon interiors openlayers.org
ol.style.Stroke Stroke style for polygon borders openlayers.org

FAQ

How do I create a polygon with a hole?

Pass a second ring array after the outer ring. The second ring defines the hole boundary using the opposite winding order.

Can I make the polygon interactive?

Yes. Use map.forEachFeatureAtPixel() in a click or pointer handler to detect when the user interacts with the polygon.

Common mistakes

  • Not closing the ring: the first and last coordinate must be the same
  • Forgetting the double array wrapper [[ ]]: the outer array holds rings, the inner array holds coordinates
  • Using opaque fills that hide the basemap: use rgba colors with low alpha values
auto_awesome

Build maps using OpenLayers with AI

Generate code like this polygon features in openlayers example using the OpenLayers skill in your IDE.