Kuidas luua Gatsby, React Leaflet & GraphCMS abil reisikopade loendi kaarti

Reisimine on lõbus ja meil kõigil on palju kohti, mida soovime külastada, kuid harva on meil aega seda korraga teha. Selleks on ämbrinimekirjad! Kuidas saaksime luua kohandatud kaardirakenduse, mille abil saaksime kõiki sihtkohti oma ämbrite loendis näidata?

  • Mida me ehitame?
  • 1. samm: uue rakenduse loomine Gatsby Starter Leafletiga
  • 2. samm: reisikohtade loendi loomine ja haldamine GraphCMS-i abil
  • 3. samm: meie GraphCMS-i asukohaandmete pärimine Gatsby ja GraphQL-iga
  • 4. samm: sihtkohtade loendi loomine ja nende lisamine kaardile
  • Milliseid muid funktsioone saame veel oma rakendusse lisada?
  • Kas soovite kaartide kohta rohkem teada saada?

Mida me ehitame?

Ehitame CMS-i hallatava kaardirakenduse Gatsbyga, mis kuvab kaardil nii markereid kui ka näitab meie asukohti lihtsas tekstipõhises loendis meie ämberloendi asukohtade jaoks.

Keerame rakenduse koos Gatsby Starter for Leaflet'iga üles ja seejärel kasutame GraphCMS-i abil oma kaardi asukohtade loendi loomiseks ja haldamiseks!

Woah, kaardistusrakendus?

Jep. Kui te pole varem kaartidega mänginud, ärge heituge! See pole nii hull, kui arvate ilmselt. Kui soovite alustada põhitõdesid kaardistamisest, saate kõigepealt lugeda, kuidas kaardistamine töötab.

1. samm: uue rakenduse loomine Gatsby Starter Leafletiga

Alustame Gatsby stardivoldikuga. See annab meile juba sisseehitatud kaardistamisvahenditega baasrakenduse React.

Uue Gatsby rakenduse loomine Gatsby Starter Leafletiga

Alustamiseks navigeerige kohta, kuhu soovite uue rakenduse luua ja käitada:

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

Märkus: saate asendada my-travel-bucket-listkõigega, mida soovite. Seda kasutatakse rakenduse uue kausta loomiseks.

Kui olete selle käivitanud, tõmbab Gatsby Starter alla ja installib sõltuvused. Kui see on lõpule jõudnud, navigeerige sellesse kataloogi ja käivitage arenduskäsk:

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

Kui asukoht on valmis, peaks teie rakendus olema kasutamiseks valmis!

Meie demokoodi puhastamine

Kuna kasutame Starterit, on sellel natuke demokoodi. Koristame selle segaduste vältimiseks välja.

Avage src/pages/index.jsfail.

Esiteks eemalda kõik sees mapEffect, välja arvatud esimene rida ja luua alias leafletElementet map:

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

Kui see on kadunud, võime eemaldada markerRefdefinitsiooni IndexPagekomponendi ülaosast , eemaldada ref={markerRef}rekvisiidi meie komponendilt ja useRefimportida React'i kõrval.

Nüüd saame eemaldada kõik muutujad, mis algavad tähega popupja time, sealhulgas:

  • timeToZoom
  • timeToOpenPopupAfterZoom
  • timeToUpdatePopupAfterZoom
  • popupContentHello
  • popupContentGatsby

Lõpuks võite eemaldada kõik järgmised read:

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

Kui see on tehtud, peaksime olema valmis põhikaardiga koos kaardiga minema!

Järgige pühendumist!

2. samm: reisikohtade loendi loomine ja haldamine GraphCMS-i abil

GraphCMS-i konto loomine

GraphCMS-iga alustamiseks vajate kontot. Ma ei hakka teid sellest osast läbi viima, kuid hea uudis on see, et neil on helde tasuta tase, mis muudab demos kasutamiseks registreerumise meile lihtsaks!

Registreeru GraphCMS-iga

Kui teil on konto juba olemas, võite veenduda, et olete sisse loginud.

Uue GraphCMS-i projekti loomine

Pärast sisselogimist soovime luua uue projekti. Me loome selle käsitsi, nii et üks kord GraphCMS juhtpaneelil valige Loo uus projekt :

Siin saate nime ja kirjelduse jaoks sisestada mis iganes soovite , näiteks:

  • Nimi: Minu reisikopade loend
  • Kirjeldus: Asukohad, kuhu tahan mingil päeval reisida!

Selle all näete kaarti, kus saate valida piirkonna . Siin hakkavad teie andmebaasi andmed elama, nii et kuigi meie eesmärkidel pole see ilmselt liiga oluline, saate valida endale kõige lähema.

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

Tutvustan teid uue @mapping-rakenduse @GatsbyJS ja @LeafletJS abil, mis näitab kõiki teie @GraphCMS-iga hallatavaid sihtkohti?

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

- Colby Fayock (@colbyfayock) 23. juuni 2020

Järgige mind, et saada rohkem Javascripti, UX-i ja muud huvitavat!

  • ? Jälgi mind Twitteris
  • ? ️ Telli Minu Youtube
  • ✉️ Registreeru minu uudiskirja saamiseks