← Back to Blog

Getting Started with OpenLayers: Your First Web Map

Follow this OpenLayers tutorial to build interactive web maps from scratch. Learn tile layers, GeoJSON vectors, custom styling, and map controls step by step.

OpenLayers is a high-performance, open-source JavaScript library for rendering interactive maps in the browser. Whether you need to display a simple tile map or build a full-featured GIS editor, this OpenLayers tutorial walks you through every foundational concept — from installation to styling vector data. By the end you will have a working map that loads tiles, renders GeoJSON features, and responds to user interactions.

Why Choose OpenLayers?

OpenLayers supports a wide range of geospatial standards out of the box, including WMS, WFS, WMTS, and GeoJSON. It is maintained by an active community and backed by the Open Source Geospatial Foundation (OSGeo). Unlike lighter libraries that focus on simplicity, OpenLayers is designed for applications that need fine-grained control over projections, layer compositing, and server-side tile protocols.

The library renders to both Canvas and WebGL, which means it can handle tens of thousands of vector features without significant performance degradation. It also provides built-in support for reprojection, so you can mix data in EPSG:4326 and EPSG:3857 without manual coordinate conversion. These capabilities make it a strong choice for enterprise dashboards, data-heavy portals, and any project that may outgrow a minimal mapping library.

Installation via npm

The recommended way to add OpenLayers to a modern project is through npm. This gives you tree-shakable ES module imports so your final bundle only includes the parts of the library you actually use.

npm install ol

If you are prototyping without a bundler, you can load the full UMD build from a CDN instead. However, the npm approach is strongly preferred for production applications because it enables dead-code elimination and integrates cleanly with tools like Webpack, Vite, and the Angular CLI.

OpenLayers Tutorial: Creating Your First Map

A minimal OpenLayers map requires three things: a target HTML element, a view that defines the center and zoom level, and at least one layer. The code below creates a map centered on London using OpenStreetMap tiles.

import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

const map = new Map({
  target: 'map',
  layers: [
    new TileLayer({
      source: new OSM()
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

The target property references the id of a <div> element in your HTML. The View accepts coordinates in the map's projection — EPSG:3857 (Web Mercator) by default. If you want to pass longitude and latitude values, use the fromLonLat helper to convert them.

import { fromLonLat } from 'ol/proj';

const view = new View({
  center: fromLonLat([-0.1276, 51.5074]),
  zoom: 10
});

Views and Projections

The View object controls what part of the world is visible and at what scale. It stores the center coordinate, the zoom level, and the rotation angle. You can constrain panning with the extent option or limit zoom with minZoom and maxZoom.

OpenLayers uses EPSG:3857 as its default projection because most tile services deliver tiles in Web Mercator. When your source data is in EPSG:4326, OpenLayers can reproject it on the fly. For specialist projections — such as polar stereographic or national grids — you can register custom definitions with the proj4 library and pass them to the view.

Tile Layers and Sources

Tile layers display pre-rendered image tiles fetched from a server. OpenLayers ships with built-in sources for OpenStreetMap, Bing Maps, Stamen, and generic XYZ tile services. The example below adds a custom XYZ tile layer alongside the default OSM layer.

import XYZ from 'ol/source/XYZ';

const satellite = new TileLayer({
  source: new XYZ({
    url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
    maxZoom: 19
  })
});

You can stack multiple tile layers and control their visibility or opacity at runtime. This is useful for toggling between street maps, satellite imagery, and thematic overlays without reloading the page.

Vector Layers with GeoJSON

Vector layers render individual features on the client side, which means you can style, filter, and interact with each feature independently. The ol/format/GeoJSON class reads GeoJSON text and converts it into OpenLayers feature objects, handling the coordinate reprojection from EPSG:4326 to the map's native projection automatically.

import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON';

const geojsonLayer = new VectorLayer({
  source: new VectorSource({
    url: '/assets/data/regions.geojson',
    format: new GeoJSON()
  })
});

For inline data you can pass a GeoJSON object directly to the source using features: new GeoJSON().readFeatures(geojsonObject, { featureProjection: 'EPSG:3857' }). When working with large datasets you may want to convert between formats first — GeoJSON to KML or KML to GeoJSON — before loading data into the map.

Styling with ol/style

OpenLayers separates data from presentation through its style module. Each feature can receive a Style composed of a Fill, a Stroke, and an image such as Circle or Icon. You can assign a single style to an entire layer or pass a function that returns different styles based on feature properties.

import { Style, Fill, Stroke, Circle as CircleStyle } from 'ol/style';

const pointStyle = new Style({
  image: new CircleStyle({
    radius: 6,
    fill: new Fill({ color: '#3b82f6' }),
    stroke: new Stroke({ color: '#1e3a5f', width: 2 })
  })
});

const polygonStyle = new Style({
  fill: new Fill({ color: 'rgba(59, 130, 246, 0.3)' }),
  stroke: new Stroke({ color: '#3b82f6', width: 2 })
});

Dynamic styling is where OpenLayers excels. By providing a style function to the layer, you can implement choropleth maps, cluster visualizations, or conditional symbology with full access to each feature's attributes at render time.

Interactions: Select, Draw, and Modify

Interactions let users manipulate map data directly. OpenLayers includes interaction classes for selecting features, drawing new geometries, modifying existing shapes, and snapping to nearby vertices. The following example adds a draw interaction that lets users sketch polygons on the map.

import Draw from 'ol/interaction/Draw';

const draw = new Draw({
  source: geojsonLayer.getSource(),
  type: 'Polygon'
});

map.addInteraction(draw);

draw.on('drawend', (event) => {
  const feature = event.feature;
  console.log('New polygon drawn:', feature.getGeometry().getCoordinates());
});

You can combine Select and Modify interactions to allow users to click a feature and drag its vertices. This pattern is the foundation for browser-based GIS editors. Once editing is complete, export the modified features as GeoJSON and visualize them instantly in GeoDataTools.

Map Controls

Controls are UI elements anchored to the map viewport. OpenLayers provides defaults for zoom buttons, attribution text, and rotation reset. You can add additional controls such as a scale line, a full-screen toggle, or a mouse position readout.

import { defaults as defaultControls } from 'ol/control';
import ScaleLine from 'ol/control/ScaleLine';
import FullScreen from 'ol/control/FullScreen';

const map = new Map({
  target: 'map',
  controls: defaultControls().extend([
    new ScaleLine({ units: 'metric' }),
    new FullScreen()
  ]),
  layers: [new TileLayer({ source: new OSM() })],
  view: new View({
    center: fromLonLat([-0.1276, 51.5074]),
    zoom: 10
  })
});

Custom controls can be created by extending the Control base class. This is useful for adding layer switchers, legend panels, or tool palettes that live inside the map container and reposition with it.

OpenLayers vs Leaflet

Both OpenLayers and Leaflet are mature, open-source mapping libraries, but they target different complexity levels. The table below summarizes the key differences to help you decide which fits your project.

Criteria OpenLayers Leaflet
Bundle size (minified) ~160 KB (tree-shaken) ~40 KB
Learning curve Steeper — more concepts to learn Gentle — minimal API surface
OGC protocol support Built-in WMS, WFS, WMTS Requires plugins
Projection handling Native reprojection engine EPSG:3857 only by default
Vector performance Canvas + WebGL rendering SVG or Canvas via plugin
Built-in drawing tools Yes — Draw, Modify, Snap No — requires Leaflet.draw plugin
Best suited for Enterprise GIS, complex workflows Lightweight maps, quick prototypes

If your project primarily displays markers and simple polygons, Leaflet's smaller footprint and simpler API may be the better choice. If you need to consume OGC services, reproject data on the fly, or build editing tools, OpenLayers provides those capabilities without relying on third-party plugins.

FAQ

Is OpenLayers free to use in commercial projects?

Yes. OpenLayers is released under the BSD 2-Clause license, which permits use in both open-source and commercial applications without royalty fees. You are free to modify and redistribute the library as long as you retain the copyright notice in source distributions.

Can OpenLayers display GeoJSON and KML on the same map?

Absolutely. You can add multiple vector layers to a single map, each with its own format parser. Use ol/format/GeoJSON for one layer and ol/format/KML for another. OpenLayers handles coordinate conversion and rendering for both formats simultaneously without any additional configuration.

How do I convert coordinates between EPSG:4326 and EPSG:3857 in OpenLayers?

Use the projection utilities included in ol/proj. The fromLonLat function converts a longitude-latitude pair to Web Mercator, and toLonLat does the reverse. For arbitrary projections, the generic transform function accepts source and destination projection codes.

Conclusion

This OpenLayers tutorial covered the core building blocks — maps, views, tile layers, vector layers, styles, interactions, and controls — that you need to build production-quality web maps. OpenLayers stands out when your project demands OGC compliance, custom projections, or advanced vector editing, and it scales gracefully from simple displays to enterprise-grade GIS applications.

Ready to see your geospatial data on a map right now? Drop a GeoJSON or KML file into GeoDataTools to visualize, inspect, and convert it instantly — no setup required.

Ready to work with your geospatial data?

Visualize, filter, and convert GeoJSON and KML files directly in your browser.

Try GeoDataTools