DEV Community

Kofi Adu Agyekum
Kofi Adu Agyekum

Posted on

Getting started with Openlayers in React

CONTENT

  1. Introduction to Maps and Openlayers
  2. Openlayers
  3. Attributes
  4. Setting up project
  5. Summary

Introduction to Maps and OpenLayers

Ever dreamt of building interactive maps to explore or showcase data? This article dives into the powerful duo of React and OpenLayers, transforming your web pages into dynamic geo-discovery tools.

Openlayers

Openlayers is a JavaScript library that is used to render onto or embed maps into a webpage. It is a free and opensource library that allows users to display maps and load vector data and markers from any data source. (https://openlayers.org/)

It is a powerful and versatile tool that allows developers to build a range of applications, from simple maps to complex, and highly interactive geospatial applications with JavaScript.

Attributes

Openlayers has 4 key components that are used to create and render maps. These are Map, View, Source and Layer.

  • Map, in openlayers, is the map container for rendering any map. Imported from the module: ol/map , it needs a target container (e.g a div) to contain the map.


import Map from "ol/map"

const map = new Map({target: 'map'})


Enter fullscreen mode Exit fullscreen mode

To display the map on your webpage, simply add an 'id' attribute to the container element of the map with the same name as the target in the newly created map above. Feel free to choose any name for the target as long as it matches the HTML element's ID.



<div id="map" style="width: 100%; height: 400px"></div>


Enter fullscreen mode Exit fullscreen mode
  • View is the part of the map creation responsible for centering, zooming and projection of the map. It is imported from the ol/view module. A View comes with a projection, which decides how coordinates are handled and what units are used for map resolutions. If you don't choose one, it defaults to Spherical Mercator (EPSG:3857), using meters as the unit for maps. The view attribute is added as an option to the new map created in the Map column above. ```tsx

import Map from "ol/map"
import View from "ol/view"

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

The center attribute specifies the initial center coordinate of the map view. It's an array with two elements representing the longitude and latitude of the center point on the map. In the above example, the map will be centered where both the longitude and latitude is zero (0). 

The zoom attribute sets the initial zoom level of the map. It is used to set how magnified or shrunk the map is compared to its default setting. You also have the option to define both _minZoom_ and _maxZoom_, allowing you to specify the minimum and maximum levels of zoom that users can apply to the map.

For example: let's make the Colosseum in Rome our starting point. Just plug in the EPSG:3857 coordinates, which you can find here: https://epsg.io/map#srs=4326&x=0.000000&y=0.000000&z=1&layer=streets. Then, zoom in or out as you please!

```tsx


import Map from "ol/map"
import View from "ol/view"

const map = new Map({
  target: 'map', 
  view: new View({
      center: [1390659.798668, 5144570.023792],
      zoom: 17,
  }),
})


Enter fullscreen mode Exit fullscreen mode

The result will look like this:

A map centered on the Colosseum

As you can see, the map is centered on the Colosseum.

  • Source is used to define the origin of spatial data that is displayed on the map. Openlayers support a variety of sources such as Tile sources like OpenStreetMap (OSM), Image sources like Web Map Service (WMS), Vector sources and XYZ sources.


import OSM from 'ol/source/osm';

const source = OSM();


Enter fullscreen mode Exit fullscreen mode

This code grabs the OpenStreetMap data and prepares it to be shown on a map.

  • Layer, simply put is the visual representation of a data source. Examples include Tile layers, Image Layers and Vector Layers.


import TileLayer from 'ol/layer/tile';

const layer = new TileLayer({source: source});


Enter fullscreen mode Exit fullscreen mode

For further reading visit (https://openlayers.org/doc/tutorials/concepts.html)

Setting up Openlayers in React

To create a map, you can merge all the essential components into one script as shown below:

First set up openlayers in react:



npm install ol
# or
yarn add ol


Enter fullscreen mode Exit fullscreen mode

In the MapView component (Typescript):



import React, { useEffect } from "react";
import "ol/ol.css";
import Map from "ol/map";
import View from "ol/view";
import TileLayer from "ol/layer/tile";
import OSM from "ol/source/osm";

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

    return () => {
      map.setTarget(null);
    };
  }, []);
return <div id="map" style={{width: "100%", height: "400px"}}/>;
}

export default MapView


Enter fullscreen mode Exit fullscreen mode

The return statement in the useEffect ensures proper cleanup and management of resources associated with the map, thereby maintaining system efficiency and stability.

MapView component (Javascript):



import React, { useEffect } from "react";
import Map from "ol/Map.js";
import View from "ol/View.js";
import TileLayer from "ol/layer/Tile.js";
import OSM from "ol/source/OSM";
import "ol/ol.css";

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

    return () => {
      map.setTarget(null);
    };
  }, []);

  return <div id="map" style={{ width: "100%", height: "400px" }} />;
}

export default MapView;



Enter fullscreen mode Exit fullscreen mode

The above code snippet will display a basic OpenStreetMap (OSM) like this:

Full map render

Summary

In our review, we've explored OpenLayers, a tool designed for creating maps, and delved into its integration with React. Through this exploration, we've gained insights into showcasing maps on our web pages by combining OpenLayers with React.

Top comments (6)

Collapse
 
pokumars profile image
Oheneba Poku-Marboah

Great article mate- can't wait to try it out soon.

Collapse
 
kofiadu profile image
Kofi Adu Agyekum • Edited

Thanks !!

Collapse
 
anthonyenn profile image
Anthony Enninful

Really insightful and detailed. Great job πŸ‘

Collapse
 
kofiadu profile image
Kofi Adu Agyekum

Thanks. I'm glad you liked it

Collapse
 
geroson profile image
Henry

Great detailing!! Keep it rolling!!

Collapse
 
pg13 profile image
Kwame Agyekum

You make me want to code again