Mapping with GatsbyJS

Using ROAR geo data

Problem: You want to do rawwwww!

Solution: Blah de blah ssfdas dasdasdsda

Find the code at https://github.com/andrewl/geogatsby/examples/simplemap

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}>
        <TileLayer
          url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
          attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
        />
        {this.props.markerText !== "" &&
        <Marker position={this.props.position}>
          <Popup>{this.props.markerText}</Popup>
        </Marker>
        }
      </Map>
    );
}

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

<Layout>
  <h1>Simple Leaflet Map</h1>
  {typeof window !== 'undefined' &&
      <SimpleLeafletMap
        position={[52,-0.5]}
        zoom={8}
        markerText={"Hello, this is a marker"}
      />
  }
</Layout>

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.