MapSnippets logo MapSnippets logo

LineString Features in OpenLayers

OpenLayers

Add a line to an OpenLayers map by placing an ol.geom.LineString feature in an ol.source.Vector and styling it with an ol.style.Stroke.

progress_activity Loading map...
var route = new ol.Feature({
  geometry: new ol.geom.LineString([
    ol.proj.fromLonLat([2.3522, 48.8566]),
    ol.proj.fromLonLat([2.2945, 48.8584]),
    ol.proj.fromLonLat([2.3272, 48.8606])
  ])
});
var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({ features: [route] }),
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({ color: '#e63946', width: 4 })
  })
});
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.32, 48.86]), zoom: 14 })
});

How to draw a line in OpenLayers

A line is created as an ol.Feature with an ol.geom.LineString geometry. The LineString constructor takes an array of coordinate pairs, each converted from longitude/latitude with ol.proj.fromLonLat().

The vector layer renders the line using ol.style.Stroke to set color and width. Multiple lines can be added to the same vector source.

Key APIs

API Description Docs
ol.geom.LineString Line geometry from array of coordinates openlayers.org
ol.style.Stroke Line stroke style (color, width, dash) openlayers.org
ol.layer.Vector Vector layer for rendering features openlayers.org

FAQ

How do I add a dashed line?

Add lineDash: [10, 10] to the ol.style.Stroke options. The array defines dash and gap lengths in pixels.

Can I add arrows or direction indicators?

OpenLayers does not have built-in arrow heads. You can place ol.style.Icon markers at line endpoints or use a style function to render arrow geometries.

Common mistakes

  • Passing raw [lng, lat] arrays without ol.proj.fromLonLat(), which puts the line in the wrong location
  • Confusing LineString (single line) with MultiLineString (collection of lines)
  • Forgetting to include ol.style.Stroke, without which the line is invisible

Build maps using OpenLayers with AI

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