Cómo crear un mapa de lista de cubo de viaje con Gatsby, React Leaflet y GraphCMS

Viajar es divertido y todos tenemos muchos lugares que queremos visitar, pero rara vez tenemos tiempo para hacerlo todos a la vez. ¡Para eso están las listas de deseos! ¿Cómo podemos crear una aplicación de mapas personalizada que podamos mostrar todos nuestros destinos en nuestra lista de deseos?

  • ¿Qué vamos a construir?
  • Paso 1: Crear una nueva aplicación con Gatsby Starter Leaflet
  • Paso 2: crear y administrar una lista de lugares de viaje con GraphCMS
  • Paso 3: Consultar nuestros datos de ubicación GraphCMS con Gatsby y GraphQL
  • Paso 4: crear una lista de destinos y agregarlos al mapa
  • ¿Qué otras funciones podemos agregar a nuestra aplicación?
  • ¿Quieres aprender más sobre mapas?

¿Qué vamos a construir?

Vamos a crear una aplicación de mapas con Gatsby administrada por un CMS que mostrará marcadores en un mapa y mostrará nuestras ubicaciones en una lista simple basada en texto para las ubicaciones de nuestra lista de deseos.

¡Haremos girar la aplicación con un Gatsby Starter for Leaflet y luego usaremos GraphCMS para crear y administrar la lista de ubicaciones para nuestro mapa!

Woah, ¿una aplicación de mapas?

Sip. Si no has jugado con mapas antes, ¡no te desanimes! No es tan malo como probablemente piensas. Si prefiere comenzar con los conceptos básicos del mapeo, primero puede leer más sobre cómo funciona el mapeo.

Paso 1: Crear una nueva aplicación con Gatsby Starter Leaflet

Empezaremos con Gatsby Starter Leaflet. Esto nos dará una aplicación React básica con nuestras herramientas de mapeo ya integradas.

Creando una nueva aplicación Gatsby con Gatsby Starter Leaflet

Para comenzar, navegue hasta donde desea crear su nueva aplicación y ejecute:

gatsby new my-travel-bucket-list //github.com/colbyfayock/gatsby-starter-leaflet 

Nota: puedes reemplazar my-travel-bucket-listcon lo que quieras. Esto se utilizará para crear la nueva carpeta de la aplicación.

Una vez que ejecute eso, Gatsby desplegará el Starter e instalará las dependencias. Una vez que esté completo, navegue hasta ese directorio y ejecute el comando de desarrollo:

cd my-travel-bucket-list yarn develop # or npm run develop 

Una vez que haya terminado la ubicación, ¡su aplicación debería estar lista para funcionar!

Limpiando nuestro código de demostración

Como estamos usando un Starter, tiene un poco de código de demostración. Limpiemos eso para evitar confusiones.

Abre el src/pages/index.jsarchivo.

En primer lugar, retire todo el interior de la mapEffectexcepción de la primera línea y establecer un alias para leafletElementque map:

async function mapEffect({ leafletElement: map } = {}) { if ( !map ) return; } 

Con eso desaparecido, podemos eliminar la markerRefdefinición en la parte superior del IndexPagecomponente, eliminar la ref={markerRef}propiedad de nuestro componente y la useRefimportación junto a React.

Ahora, podemos eliminar todas las variables que comienzan con popupy time, incluidas:

  • timeToZoom
  • timeToOpenPopupAfterZoom
  • timeToUpdatePopupAfterZoom
  • popupContentHello
  • popupContentGatsby

Por último, puede eliminar todas las siguientes líneas:

import L from 'leaflet'; ... import { promiseToFlyTo, getCurrentLocation } from 'lib/map'; ... import gatsby_astronaut from 'assets/images/gatsby-astronaut.jpg'; ... const ZOOM = 10; 

Una vez hecho esto, ¡deberíamos estar listos para usar una aplicación básica con un mapa!

¡Sigue el compromiso!

Paso 2: crear y administrar una lista de lugares de viaje con GraphCMS

Creando una cuenta GraphCMS

Para comenzar con GraphCMS, necesitará una cuenta. No voy a explicarte esta parte, pero la buena noticia es que tienen un generoso nivel gratuito que facilita el registro para que lo usemos en nuestra demostración.

Regístrese en GraphCMS

Alternativamente, si ya tiene una cuenta, puede asegurarse de haber iniciado sesión.

Creando un nuevo proyecto GraphCMS

Una vez que haya iniciado sesión, querremos crear un nuevo proyecto. Vamos a crear uno manualmente, así que una vez en GraphCMS Dashboard, seleccione Crear nuevo proyecto :

Aquí, puede ingresar lo que desee para el Nombre y la Descripción , como:

  • Nombre: Mi lista de viajes pendientes
  • Descripción: ¡Los lugares a los que quiero viajar algún día!

Debajo verá un mapa en el que seleccionará una región . Aquí es donde vivirán los datos de su base de datos, por lo que aunque probablemente no importe demasiado para nuestros propósitos, puede elegir el que esté más cerca de usted.

After you select your options, go ahead and click Create Project.

Next, you’ll be presented with billing options. Since we’re just creating a demo, under Personal select Continue at which point we’ll be dropped into our new GraphCMS project dashboard.

Creating a new Content Model Schema with GraphCMS

In GraphCMS, a Content Model refers to a specific type of data that has specific properties associated with it. In our case, our Model will be a Destination, which will be defined by a Name and a Location.

First, navigate to the Schema section of GraphCMS in the left sidebar and select Create Model.

Once selected, you’ll see a popup that asks for a bit more information. Here, you can type in “Destination” as the Display Name, which will also fill in most of the other fields. We’ll leave those as is.

Feel free to add a description if you’d like, but it’s not required. Then select Create model.

Now that we have our Model, we need our properties.

First, select Single line text in the right list of fields and add a Display Name of “Name”. This will also fill out App Id which you can leave as is. Then click Create.

Next, scroll down in the field options on the right and under Location select Map. Add “Location” as the Display Name, which will set the App Id as “location” which you can leave as is. Then same as before, click Create.

Now we have a Content Model which we’ll use to create our locations!

Creating our locations

Finally, let’s create our locations. Navigate over to Content in the GraphCMS dashboard, make sure you’ve selected Destination under System (should be the only one), and select Create New.

Now we can start adding all of our locations! First, add the name of your location in the Name field, then you can use the Search box under Location to find that location on the map.

Once you’re good, hit Save and publish. This will create your first location!

Follow those same steps and create as many locations as you want.

We’ll use these for our map and bucket list.

Step 3: Querying our GraphCMS location data with Gatsby and GraphQL

Now that we have our locations, let’s use them!

Adding a plugin to Gatsby to query our GraphQL data

First, we need to add a new plugin to our Gatsby project to query our GraphQL data. In your terminal make sure your development server isn’t running and run:

yarn add gatsby-source-graphql # or npm install gatsby-source-graphql 

Next, open up your gatsby-config.js file in the root of your project and add the following to your plugins:

{ resolve: 'gatsby-source-graphql', options: { typeName: 'GCMS', fieldName: 'gcms', url: '[API ENDPOINT]', } } 

This will be what sources our data from GraphCMS, but we need an endpoint.

Finding our API endpoint for GraphCMS

Open back up your browser and head over to your GraphCMS project. After selecting Settings in the left navigation, select API Access.

Before we copy our API Endpoint, first we need to update our permissions so we can query our API. Under Public API Permissions, check the box next to Content from stage Published and click Save.

Next, copy the URL under Endpoints:

And paste that in to your gatsby-config.js file that we modified above:

{ resolve: 'gatsby-source-graphql', options: { typeName: 'GCMS', fieldName: 'gcms', url: '//[region-id].graphcms.com/v2/[project-id]/master', }, }, 

Note: your URL will have actual values inside of [region-id] and [project-id].

Save your gatsby-config.js file and start your development server backup (yarn develop) and we’re ready to go!

Querying our locations via GraphQL

Finally, let’s actually query our data so that we’ll be able to use it in our app.

We’re going to create a new React Hook that we’ll be able to use to grab our locations anywhere within our app.

Under src/hooks/index.js, add the following line to the existing list:

export { default as useDestinations } from './useDestinations'; 

This will allow us to more conveniently import our hook which we’ll create next.

Under src/hooks, create a new file useDestinations.js and paste in this code:

import { graphql, useStaticQuery } from 'gatsby'; export default function useDestinations() { const { gcms = {} } = useStaticQuery( graphql` query { gcms { destinations { id name location { latitude longitude } } } } ` ); let { destinations } = gcms; return { destinations, }; } 

Here, we’re:

  • Importing the graphql and useStaticQuery utilities from Gatsby
  • We’re creating a new function (or hook) that is exported by default
  • In that function, we’re using useStaticQuery to create a new GraphQL query which asks GraphCMS to return the data structure we defined.
  • That query returns a value which we destructure immediately to grab the gmcs object
  • We destructure destinations from gmcs and return it as part of a new object from our hook

With this, we can now use our hook anywhere in our app!

Head over to your src/pages/index.js file, first import our new hook:

import { useDestinations } from 'hooks'; 

And at the top of the IndexPage component, query our data:

const { destinations } = useDestinations(); 

This puts all of our locations into the destinations variable. We can test that this works by console logging it out:

console.log('destinations', destinations); 

And once we open up our browser and look in our web developer tools console, we can see our location data!

Step 4: Creating a bucket list of destinations and adding them to the map

We’re going to start with creating a simple text list of our destinations. This will let us see all of our destinations in an easy to read format.

Creating a text list of our destinations

Inside of our IndexPage and above “Still Getting Started?”, let’s add the following code:

My Destinations

    { destinations.map(destination => { const { id, name } = destination; return
  • { name }
  • })}

This code:

  • Adds a new header for our list
  • Creates a new unordered list
  • Loops through our destinations and creates a new list item for each destination that include’s the location’s name

Once we hit save and reload, we should see our list under our map!

The list looks a little odd though right? We probably want to format it a little better to fit into the page.

Open up src/assets/stylesheets/pages/_home.scss and inside of the .home-start class, add:

.home-start { ... ul { list-style: none; padding: 0; margin: 1.2em 0; } 

Let’s also modify the h2 to space things out a little better:

.home-start { ... h2 { margin-top: 2em; &:first-child { margin-top: 0; } } 

Once you hit save and reload, it should look a little better.

Feel free to make additional changes, but we’ll leave it there for now.

Adding our destinations to the map

Now we can finally add our destinations to the map!

Inside of our component, we already have a . This allows us to easily add a marker to the map given a position. We’ll take this concept and combine it with our text list to add our locations to the map.

Let’s update our code to match the following:

 { destinations.map(destination => { const { id, name, location } = destination; const position = [location.latitude, location.longitude]; return  })}  

Here we:

  • Loop through our destinations to dynamically create a new list of components inside our
  • Inside each loop instance, we destructure our date from destination
  • We create a new position array with the latitude and longitude
  • Create a new Marker where we use our position to add it to the map

This gives us our markers on the map!

But we want to know what each of those locations are, so let’s also add a popup to each marker that will show the name.

First, we need to import Popup from react-leaflet:

import { Marker, Popup } from 'react-leaflet'; 

Then, let’s update our component to return:

return (  { name }  ); 

And once we save and open back up our map, you can now click on each marker and see our destinations name!

Before we’re done, center the map

Previously, our demo map centered on Washington, DC. Let’s update that to the center of the world since our map doesn’t focus on the United States.

Update the LOCATION variable to:

const LOCATION = { lat: 0, lng: 0, }; 

And with that, we have our map!

Follow along with the commit!

What else other features can we add to our app?

Add a way to check off each location

Inside GraphCMS, you can add a new field to your Destination content model that allows you to select whether you visited each location or not.

With this value, we can add it to our query and update our map with some kind of indicator like a checkmark to show that we’ve checked it off our bucket list!

Customize your map background styles

We’re using a public version of OpenStreetMap which is open source, but Mapbox offers some cool maps we can use to make it look a little more impressive.

If you want to get started changing your map styles, you can check out this other walkthrough of mine to learn how to use Mapbox.

Check out the blog post or watch the video!

Style the map markers with a custom image

You can check out my video walk through on how to change the markers to a custom image.

Take that a step further and use the feature above to dynamically show a different marker image when you’ve checked off a location.

Check out the video on Egghead.io!

Want to learn more about maps?

Check out some of my other tutorials and videos:

  • Mapping with React Leaflet (egghead.io)
  • Mapping Apps with React, Gatsby, & Leaflet (youtube.com)
  • How to create a Coronavirus (COVID-19) Dashboard & Map App with Gatsby and Leaflet (colbyfayock.com)
  • How to Create a Summer Road Trip Mapping App with Gatsby and Leaflet (colbyfayock.com)
  • How to build a mapping app in React the easy way with Leaflet (colbyfayock.com)
  • Anyone Can Map! Inspiration and an introduction to the world of mapping (colbyfayock.com)

What’s on your travel bucket list?

Let me know on Twitter!

Want to learn how to create a Travel Bucket List with all your dream destinations? ??

Te guío a través de la creación de una nueva aplicación de #mapeo con @GatsbyJS y @LeafletJS que muestra todos tus destinos administrados con @GraphCMS.

? #webdev # 100DaysOfCode // t.co / 1hhWiQOfYw

- Colby Fayock (@colbyfayock) 23 de junio de 2020

¡Sígueme para obtener más Javascript, UX y otras cosas interesantes!

  • ? Sigueme en Twitter
  • ? ️ Suscríbete a mi Youtube
  • ✉️ Suscríbete a mi boletín