Andrew Larcombe

Adding a map to your Gatsby site

Want to add a map to your Gatsby pages? These simple instructions will get you started with a map, a marker which displays a popup when clicked. To see what I'm talking about you can visit the demo at https://andrewl.github.io/gatsby-geo-simple-map

To display the maps we'll be using Leaflet. Leaflet is "an open source JavaScript libray for mobile-friendly interactive maps - you can find more about Leaflet over at https://leafletjs.com

Assuming you have a Gatsby site up and running, the first thing you'll need to do is add the following npm packages, which installs Leaflet and the React and Gatsby wrappers for it


npm i --save leaflet react-leaflet gatsby-plugin-react-leaflet

It's really easy to build a React component for our site which displays a map - we'll give it three properties

  • location - a latitude and longitude pair expressed as an array (eg [-50.0, -1] for latitude -50.0, longitude -1)
  • zoom - the initial zoom level of the map
  • markerText (optional) - if supplied, this will display a marker which when clicked on will display the text

The render() method for the component is quite simple, it just substitutes the placeholders with values from the properties above and adds a little logic to determine whether or not to display a marker:

Whilst this component will work fine in develop mode, if you try to build your site with it you'll hit a webpack error. This is because of the nature of the lifecycle of React components and the fact that Gatsby uses server side rendering to build pages.

To fix this, wherever you want to use the component you need to wrap it in a simple test determining whether we're in a real browser or not. This, from index.js, demonstrates the approach

To see the full demo in action go to https://andrewl.github.io/gatsby-geo-simple-map , and you can download the complete code at https://github.com/andrewl/gatsby-geo-simple-map

I'm Andrew - a Tech Architect and Agile Delivery Consultant. Find out more about the services I offer here