Kuinka luoda matkakopio-luettelokartta Gatsbyn, React Leafletin ja GraphCMS: n avulla

Matkustaminen on hauskaa ja meillä kaikilla on paljon paikkoja, joissa haluamme vierailla, mutta harvoin meillä on aikaa tehdä se kerralla. Tätä varten ämpäri luettelot ovat! Kuinka voimme luoda mukautetun kartoitussovelluksen, jonka avulla voimme näyttää kaikki kohteemme ämpärien luettelossa?

  • Mitä aiomme rakentaa?
  • Vaihe 1: Uuden sovelluksen luominen Gatsby Starter Leaflet -sovelluksella
  • Vaihe 2: Luodaan ja hallitaan matkakohteiden luettelo GraphCMS: n avulla
  • Vaihe 3: Kysytään GraphCMS-sijaintitietojamme Gatsbyn ja GraphQL: n avulla
  • Vaihe 4: Luodaan määränpäiden luettelo ja lisätään ne karttaan
  • Mitä muita ominaisuuksia voimme lisätä sovellukseemme?
  • Haluatko oppia lisää kartoista?

Mitä aiomme rakentaa?

Aiomme rakentaa kartoitusohjelman Gatsbyn kanssa, jota hallinnoi CMS, joka näyttää sekä merkinnät kartalla että näyttää sijaintimme yksinkertaisessa tekstipohjaisessa luettelossa ryhmäluettelomme sijainneille.

Kehitämme sovellusta Gatsby Starter for Leaflet -sovelluksella ja käytämme sitten GraphCMS: ää luodaksemme ja hallinnoidessamme karttamme sijaintiluetteloa!

Woah, kartoitussovellus?

Jep. Jos et ole pelannut kartoilla aiemmin, älä lannistu! Se ei ole niin paha kuin luultavasti luulet. Jos haluat mieluummin aloittaa kartoituksen perusteista, voit lukea lisää siitä, miten kartoitus toimii ensin.

Vaihe 1: Uuden sovelluksen luominen Gatsby Starter Leaflet -sovelluksella

Aloitamme Gatsbyn aloituslehdestä. Tämä antaa meille perustason React-sovelluksen jo rakennetuilla kartoitustyökaluillamme.

Uuden Gatsby-sovelluksen luominen Gatsby Starter Leaflet -sovelluksella

Aloita siirtymällä kohtaan, johon haluat luoda uuden sovelluksen ja suorittaa:

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

Huomaa: voit korvata my-travel-bucket-listhaluamasi. Tätä käytetään sovelluksen uuden kansion luomiseen.

Kun olet suorittanut sen, Gatsby vetää Starterin alas ja asentaa riippuvuudet. Kun se on valmis, siirry kyseiseen hakemistoon ja suorita kehityskomento:

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

Kun se on valmis, sovelluksesi on oltava valmis aloittamaan!

Puhdistamme demokoodimme

Koska käytämme Starteria, siinä on vähän demokoodia. Siivotaan se pois sekaannusten välttämiseksi.

Avaa src/pages/index.jstiedosto.

Poista ensin kaikki sisällä mapEffectpaitsi ensimmäinen rivi ja perustaa alias leafletElementon map:

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

Kun tämä on poissa, voimme poistaa markerRefmääritelmän IndexPagekomponentin yläosasta , poistaa ref={markerRef}potkurin komponentistamme ja useReftuonnin React- kohdan vierestä.

Nyt voimme poistaa kaikki muuttujat, jotka alkavat popupja time, mukaan lukien:

  • timeToZoom
  • timeToOpenPopupAfterZoom
  • timeToUpdatePopupAfterZoom
  • popupContentHello
  • popupContentGatsby

Lopuksi voit poistaa kaikki seuraavat rivit:

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

Kun se on tehty, meidän pitäisi olla valmiita käyttämään karttasovellusta!

Seuraa sitoutumista!

Vaihe 2: Luodaan ja hallitaan matkakohteiden luettelo GraphCMS: n avulla

GraphCMS-tilin luominen

Tarvitset tilin, jotta voit aloittaa GraphCMS: n käytön. En aio käydä läpi tätä osaa, mutta hyvä uutinen on, että heillä on antelias ilmainen taso, jonka avulla on helppo rekisteröityä meille, jotta voimme käyttää demoamme!

Rekisteröidy GraphCMS: ään

Vaihtoehtoisesti, jos sinulla on jo tili, voit varmistaa, että olet kirjautunut sisään.

Uuden GraphCMS-projektin luominen

Kun olet kirjautunut sisään, haluamme luoda uuden projektin. Luomme sellaisen manuaalisesti, joten valitse kerran GraphCMS-hallintapaneelista Luo uusi projekti :

Täällä voit kirjoittaa haluamasi nimen ja kuvauksen , kuten:

  • Nimi: My Travel Bucket List
  • Kuvaus: Paikat, joihin haluan matkustaa jonain päivänä!

Sen alapuolella näet kartan, josta valitset alueen . Täällä tietokantasi tiedot elävät, joten vaikka sillä ei todennäköisesti ole väliä liikaa tarkoituksissamme, voit valita lähimpänä olevan.

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? ??

Opastan sinua pyörittämään uutta #mapping-sovellusta @GatsbyJS: n ja @LeafletJS: n avulla, joka näyttää kaikki kohteesi, joita hallinnoidaan @GraphCMS: llä?

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

- Colby Fayock (@colbyfayock) 23. kesäkuuta 2020

Seuraa minua saadaksesi lisää Javascriptiä, UX: ää ja muita mielenkiintoisia asioita!

  • ? Seuraa minua Twitterissä
  • ? ️ Tilaa Youtube
  • ✉️ Rekisteröidy uutiskirjeeseen