Mapping with GatsbyJS

Simple Map

Problem: You want do embed a map on a page, perhaps with a marker and a popup

Solution: Build a component based using the gatsby-plugin-leaflet-react plugin

Find the code at

See the demo at /simplemap/index.html

This is a very common use case - you want to embed a map on a page, and maybe include a marker which when clicked shows a popup information box.

We can achieve this using Leaflet. Leaflet is "an open source JavaScript libray for mobile-friendly interactive maps"

Building on top of React-Leaflet, a library of components which "leverages React's lifecycle methods" we can construct a SimpleMap component for our site which takes 3 properties:

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

The render() method for the component is quite simple:

render() {
    return (
      <Map center={this.props.position} zoom={this.props.zoom}>
          attribution="&copy; <a href=&quot;;>OpenStreetMap</a> contributors"
        {this.props.markerText !== "" &&
        <Marker position={this.props.position}>

To embed the component on a page though we need take one simple precaution. If we try to include any of the leaflet libraries during a gatsby build we'll encounter a webpack error. To circumvent this we need to check whether window is defined, and if it is we render the SimpleComponent. This, from index.js demonstrates the approach

  <h1>Simple Leaflet Map</h1>
  {typeof window !== 'undefined' &&
        markerText={"Hello, this is a marker"}

This displays a map centered on latitude 52, longitude -0.5, with a zoom level 8, and a marker, which when clicked up will display a popup with the text "Hello, this is a marker".

To see this in action, click here.