Kako stvoriti vlastiti tragač Djeda Mraza s Gatsbyem i React Leafletom

Božićno je doba čarobno doba godine. Djeda Mraza leti okolo šireći veselje i vilenjake u romanju po New Yorku tijekom našeg godišnjeg ponovnog gledanja s obitelji i prijateljima.

Da bismo ušli u duh, zavrtit ćemo web aplikaciju koja uključuje kartu koja na njoj prati Djeda Mraza!

Uredi 12/23: Ažurirano je aplikacija tako da zatraži izravno put Djeda Mraza, samo u slučaju da izvorni API ne radi kako se prvotno očekivalo.

Što ćemo graditi?

Radit ćemo na izradi aplikacije za mapiranje koja prati Djedovu rutu i njegovo trenutno mjesto.

Da bismo to postigli, zavit ćemo unaprijed izrađeni Gatsbyjev pokretač koji će nam dati osnovne temelje za kartu, upotrijebiti Googleov neslužbeni API za hvatanje Djedove rute i prekrivati ​​njegov položaj i put na vrhu karte pomoću letaka.

Woah, aplikacija za mapiranje?

Da. Ako se prije niste igrali s kartama, nemojte se obeshrabriti! Nije tako loše kao što vjerojatno mislite. Ako biste radije započeli s osnovama mapiranja, možete pročitati više o tome kako mapiranje prvo djeluje.

Što trebamo prije nego započnemo?

Za ovu vježbu pretpostavit ću da ste instalirali čvor ili pređu. Za svaki primjer koristit ću pređu, ali upotrijebite alat po vašem izboru.

Također ćete htjeti instalirati Gatsbyjev CLI globalno, što će nam omogućiti upotrebu njihovih Starter alata.

Da biste postavili Gatsbyjev CLI, pokrenite sljedeću naredbu:

yarn global add gatsby-cli

Nakon toga trebali biste moći pokrenuti gatsby -hda biste vidjeli dostupne naredbe, što znači da je uspješno instalirana.

Za više informacija o Gatsby CLI, možete pogledati njihovu dokumentaciju.

Početak rada s našim temeljem karte

Jednom kada su postavljeni naši alati naredbenog retka, prvo što ćemo htjeti je stvoriti novi Gatsby projekt koristeći letak koji sam sastavio. Pruža nam osnovnu postavku za Leaflet i React Leaflet.

Počevši od direktorija vašeg projekta, instalirajmo projekt:

gatsby new [directory] //github.com/colbyfayock/gatsby-starter-leaflet 

Obavezno zamijenite [directory]mjestom na kojem želite postaviti svoj projekt.

Jednom kada pokrenete tu naredbu, Gatsby će klonirati taj projekt bez ijedne git reference i instalirati pakete potrebne za pokretanje.

Da biste bili sigurni da radi, sada možete otići do tog direktorija, okrenuti poslužitelj i testirati ga u pregledniku:

cd [directory] yarn develop 

Tamo gdje vidite [directory]gore, pri postavljanju novog Gatsby projekta pobrinite se za isti put kao i prije.

Ako sve bude kako je planirano, vaš bi se poslužitelj trebao pokrenuti i sada biste u pregledniku mogli vidjeti svoju osnovnu aplikaciju za mapiranje!

Čišćenje stvari

Ovaj početak nudi brzi primjer kako možemo komunicirati s zemljovidom. Ovo nam uopće neće trebati za naše svrhe, pa ćemo moći počistiti stvari.

Za početak ćemo otvoriti svoju index.jsdatoteku, datoteku početne stranice i riješiti se svega unutar mapEffectfunkcije, što nam ostavlja:

// In src/pages/index.js async function mapEffect({ leafletElement } = {}) { // Get rid of everything in here } 

Sada, uklonimo Markerkomponentu ugniježđenu unutar našeg Map, pa ćemo završiti s:

Sada kada više ne koristimo tu funkcionalnost, možemo se riješiti varijabli i referenci na vrhu datoteke, tako da možete nastaviti i ukloniti:

  • useRef
  • promisToFlyTo
  • getCurrentLocation
  • Marker
  • gatsby_astronaut
  • ZUM
  • timeToZoom
  • timeToOpenPopupAfterZoom
  • timeToUpdatePopupAfterZoom
  • popupContentHello
  • popupContentGatsby
  • markerRef

Slijedite uz predavanje.

Pronalaženje Djeda Mraza

Sad kad smo na dobrom mjestu, uprljajmo ruke i pronađimo Djeda Mraza. Da bismo to učinili, koristit ćemo Googleov neslužbeni API bez dokumenata. To znači da je moguće da ovaj API neće biti dostupan dan nakon objavljivanja ovog nabave, ali budimo optimistični.

Uz to, u vrijeme pisanja ovog članka još uvijek prikazuje prošlogodišnja odredišta, pa ono što ćemo ovdje zaista vizualizirati jest ruta Djed Božićnjaka za prošlu godinu, iako se nada da će se ovo resetirati 24. i da ćemo svi biti veseli!

Prije nego dobijemo Djeda Mraza, najprije dodamo redak u našu mapEffectfunkciju:

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

Ovo će učiniti da spriječi pokretanje ostatka našeg koda u slučaju da naša karta još nije spremna. Sama mapEffectfunkcija, kao što možete vidjeti u Mapkomponenti, izvodi se unutar instance useEffectprosljeđivanja argumenta a refna kartu, omogućujući nam pokretanje nekog koda nakon što se komponenta generira.

Dakle, jednom kad imamo tu liniju, dohvatimo sada Djedovu rutu unutar naše mapEffectfunkcije:

async function mapEffect({ leafletElement } = {}) { if ( !leafletElement ) return; let route, routeJson; try { route = await fetch('//firebasestorage.googleapis.com/v0/b/santa-tracker-firebase.appspot.com/o/route%2Fsanta_en.json?alt=media&2018b'); routeJson = await route.json(); } catch(e) { console.log(`Failed to find Santa!: ${e}`); } console.log(‘routeJson’, routeJson); }

Razdvojimo ovo:

  • Hvatamo Djed Mraz putem API krajnje točke
  • Nakon što pronađemo njegovu rutu, zgrabimo odgovor u JSON formatu kako bismo olakšali rad
  • Sve je ovo umotano u pokušaj / ulov kako bismo mogli sigurno riješiti sve pogreške odgovora
  • Konačno, zasad smo samo logodgovorili

Sada imamo Djeda Mraza i njegovu rutu, što znači da možemo vidjeti sva odredišta na njegovoj ruti. Ako malo potražite u odgovoru, možete vidjeti neke zabavne stvari, poput broja poklona koji su isporučeni na svako mjesto i vremena u to vrijeme!

Slijedite uz predavanje.

Stavite pribadaču na njegovo mjesto

Pronašli smo Djeda Mraza! ? Stavimo ga sada na kartu.

Za naše potrebe morat ćemo pronaći zemljopisnu širinu i dužinu Djeda Mraza. Problem je što mi nigdje ne definiramo točnu vrijednost, već samo dobivamo njegova odredišta.

Since we don’t have his location specified anywhere, we can utilize his last known location where presents were delivered. Add the following after our last snippet inside the mapEffect function:

const { destinations = [] } = routeJson || {}; const destinationsVisited = destinations.filter(({arrival}) => arrival  presentsDelivered > 0); const lastKnownDestination = destinationsWithPresents[destinationsWithPresents.length - 1]

Below our request code, we:

  • Destructure routeJson to grab destinations into a constant, adding a fallback to an empty object
  • Filter the results to only find the destinations that he's visited, using the arrival time from the route object
  • Filter the results to find only the locations with presents
  • And finally grab the last item from the array, which shows his last known location

At this point in time, 12/23, we don't actually have any destinations, as Santa is still at the North Pole. At any time, we can test this out to simulate a future date by replaceing Date.now() in destinationsVisited with a future date, such as 1577188980000 which would be around 7pm Eastern on 12/24. With that change, we can see what Santa's route actually looks like!

Handle a missing Santa

Now that it's close to Christmas, Santa will still be at the North Pole, so let's handle the case where we don't have a location.

Above the line where we set lastKnownDestination, let's add:

if ( destinationsWithPresents.length === 0 ) { // Create a Leaflet Market instance using Santa's LatLng location const center = new L.LatLng( 0, 0 ); const noSanta = L.marker( center, { icon: L.divIcon({ className: 'icon', html: ` ? `, iconSize: 50 }) }); noSanta.addTo( leafletElement ); noSanta.bindPopup( `Santa's still at the North Pole!` ); noSanta.openPopup(); return; }

Okay so what are we doing here?

  • First, we’re checking if we have any destinations with presents, which here we don't
  • We first create a LatLng of the center of the map
  • We create a Leaflet marker, using that center, with a custom Icon of Santa
  • Next we add that Santa marker to the leafletElement, which is our map
  • To show a message, we first bind a popup with a custom message and open it
  • Finally we return so the rest of the code doesn’t run, as we don’t have Santa at this point

This was a section added after published to handle the API resetting, but you can still follow along with the code I added in context of the rest of the rest of the code.

Follow along in the code.

Pinning Santa

Edit 12/23: This section was originally written with the previous year's API, but this is still a good example of what you'll expect on the response, so you can follow right along.

And as we can see, since we’re looking at last year’s data, Santa is back home at the North Pole.

With his location, we can pull that apart, set up a Leaflet marker instance, and add our old friend to the map. Add the following after our last snippet inside the mapEffect function:

const santaLocation = new L.LatLng( lastKnownDestination.location.lat, lastKnownDestination.location.lng ); const santaMarker = L.marker( santaLocation, { icon: L.divIcon({ className: ‘icon’, html: ` ? `, iconSize: 50 }) }); santaMarker.addTo(leafletElement);

Here we:

  • Create a Leaflet LatLng instance with his location
  • Create a Marker instance with our newly created LatLng instance
  • Add our new Marker to the map

If we refresh our page, you’ll have to zoom out and pan up a little bit, but we'll see Santa on the map!

Before we move on, let’s give Santa a little holiday cheer to make him easier to find. Find your application.scss file and toss these styles in:

// In src/assets/stylesheets/application.scss .icon { & > div { display: flex; justify-content: center; align-items: center; overflow: hidden; border-radius: 100%; box-shadow: 0 3px 4px rgba(0,0,0,.4); border: none; transition: all .2s; &:hover { box-shadow: 0 4px 8px rgba(0,0,0,.6); } } } .icon-santa { width: 50px; height: 50px; font-size: 3em; background: white; } 

This just adds a white circle around him, a little drop shadow, and increases the size a bit to make him a little easier to find on the map.

Follow along with the commit.

Drawing his route

The last thing we’re going to do here is draw a path on the map showing his route so we can follow along.

To get started, let’s update our code and add this last bit after our last snippet in the mapEffect function:

// Create a set of LatLng coordinates that make up Santa's route const santasRouteLatLngs = destinationsWithPresents.map(destination => { const { location } = destination; const { lat, lng } = location; return new L.LatLng( lat, lng ); }); // Utilize Leaflet's Polyline to add the route to the map const santasRoute = new L.Polyline( santasRouteLatLngs, { weight: 2, color: 'green', opacity: 1, fillColor: 'green', fillOpacity: 0.5 }); // Add Santa to the map! santasRoute.addTo(leafletElement); 

What we’re doing:

  • Creating an array of Leaflet LatLng instances that make up Santa’s route
  • Creating a Leaflet Polyline (a multi-point line) using that routes array
  • Make that Polyline green
  • Add our Polyline to the map

What we get… is a bunch of squiggly lines!

This is expected. This gets technical really fast, but Leaflet by default can only understand 1 “portion” of the map as it wraps around in our browser. What this realistically means, is instead of drawing a line around a globe, the coordinates think it goes from one side of the world to the other as it hits the International Dateline. This is a bit out of scope for this tutorial, but you can check out Leaflet.Antimeridian to learn more and see if you can implement the solution to it.

Follow along with the commit.

A few quick style tweaks

One last thing! And this is completely optional. Let’s make the map a little bit bigger, set the background color to match our oceans, and zoom out a little bit. So let’s make a few changes:

// In src/pages/index.js const DEFAULT_ZOOM = 1; 

We’re setting our default zoom to 1 instead of 2 to allow the map to be zoomed out a bit.

// In src/assets/stylesheets/pages/_home.scss .page-home { .map, .map-base { height: 80vh; } }

We’re setting our map to a height of 80vh instead of 50vh to make it take up a little more of our screen.

// In src/assets/stylesheets/components/_map.scss .map { &, .map-base { background: #acd3de; } }

We’re setting the background color of our map to #acd3de instead of $blue-grey-50 which allows us to match the color of the oceans on our map.

What this achieves is being able to see Santa’s full route and Santa on the first view. Additionally, since the map only covers part of the screen, setting the background color of the map allows us to not have a little bit of a weird cutoff.

Follow along with the commit.

Want a challenge?

To take this 1 step further, follow along with both how we added the routes and Santa to the map and try to see if you can add a marker to each destination location to show where all of the stops are. Bonus, add a popup to each one that says how many presents were delivered to that location!

To see the answer with some code organization and how I added the gift markers, check out the final version of the Santa Tracker demo.

While you’re there, you can also see how I utilized Leaflet.Antimeridian to fix our map's route.

What did we learn?

Building basic apps with a map isn’t nearly as bad as we thought! We learned how to fetch some data from an API, grab the data we need, and draw representations of that data on a map.

Next time you want to add a map widget to your landing page, try Leaflet. Share what you create on Twitter! Would love to see what you come up with.

I hope you and your family have a fantastic holiday season!

Want to learn more about maps?

You can check out a few of my other resources to get started:

  • Anyone Can Map! Inspiration and an introduction to the world of mapping
  • How to create a Coronavirus (COVID-19) Dashboard & Map App in React with Gatsby and Leaflet
  • How to set up a custom Mapbox basemap style with React Leaflet and Leaflet Gatsby Starter
  • How to Create a Summer Road Trip Mapping App with Gatsby and Leaflet
  • How to build a mapping app in React the easy way with Leaflet

Follow me for more Javascript, UX, and other interesting things!

  • ? Follow Me On Twitter
  • ?️ Subscribe To My Youtube
  • ✉️ Sign Up For My Newsletter

Want to read some of my other articles? Check out my blog: //www.colbyfayock.com/2019/12/create-your-own-santa-tracker-with-gatsby-and-react-leaflet/