Kuidas luua oma jõuluvana jälgija koos Gatsby ja React Leafletiga

Jõuluaeg on maagiline aastaaeg. Iga-aastase kordusvaatamise ajal koos pere ja sõpradega lendab jõuluvana ringi ja levib New Yorgis ringi päkapikk.

Vaimu saavutamiseks keerutame üles veebirakenduse, mis sisaldab kaarti, mis sellel jõuluvana jälgib!

Redigeerimine 12/23: värskendati rakendust, et taotleda otse jõuluvana marsruuti, igaks juhuks, kui algne API ei tööta algselt oodatud viisil.

Mida me ehitame?

Töötame läbi kaardirakenduse ehitamise, mis jälgib jõuluvana marsruuti ja tema praegust asukohta.

Selle saavutamiseks paneme paika eelvalmistatud Gatsby starteri, mis annab meile kaardi põhialuse, kasutab Google'i mitteametlikku API-d jõuluvana marsruudi haaramiseks ning tema asukoha ja marsruudi kaardi ülaosas lehte Leaflet.

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.

Mida me vajame enne alustamist?

Selle harjutuse jaoks eeldan, et teil on sõlm või lõng installitud. Iga näite puhul kasutan lõnga, kuid kasutan teie valitud tööriista.

Samuti peate installima Gatsby CLI globaalselt, mis võimaldab meil kasutada nende Starter tööriistu.

Gatsby CLI seadistamiseks käivitage järgmine käsk:

yarn global add gatsby-cli

Pärast seda peaksite saama käitada gatsby -holemasolevaid käske, mis tähendab, et see on edukalt installitud.

Lisateavet Gatsby CLI kohta leiate nende dokumentatsioonist.

Meie kaardi sihtasutusega alustamine

Kui meie käsurea tööriistad on seadistatud, loome esimese asjana uue Gatsby projekti, kasutades minu kokku pandud voldikute starterit. See annab meile põhiseadistused koos infolehega ja React Leaflet.

Alustades teie projektikataloogist, installime projekti:

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

Asendage see kindlasti [directory]asukohaga, mille soovite oma projekti seadistada.

Kui olete selle käsu käivitanud, kloonib Gatsby selle projekti ilma ühegi git-viita ja installib käivitamiseks vajalikud paketid.

Veendumaks, et see töötab, saate nüüd navigeerida sellesse kataloogi, keerutada oma serverit üles ja testida seda brauseris:

cd [directory] yarn develop 

Seal, kus näete [directory]ülaltoodut, kasutage uue Gatsby projekti seadistamisel kindlasti sama rada nagu varem.

Kui kõik läheb plaanipäraselt, peaks teie server käivituma ja nüüd peaksite oma brauseris nägema oma põhilist kaardistamisrakendust!

Asjade koristamine

Selle starteri juurde kuulub kiire näide selle kohta, kuidas saame kaardiga suhelda. Me ei vaja seda oma eesmärkidel üldse, et saaksime asjadega hakkama saada.

Alustuseks avame oma index.jsfaili, kodulehe faili ja vabaneme kõigest mapEffectfunktsiooni sees , mis jätab meile:

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

Nüüd eemaldame Markermeie sisse sisestatud komponendi Map, nii et jõuame lõpuks:

Nüüd, kui me seda funktsiooni enam ei kasuta, saame faili ülaosas olevatest muutujatest ja viidetest lahti, nii et võite jätkata ja eemaldada:

  • useRef
  • allowToFlyTo
  • getCurrentLocation
  • Marker
  • gatsby_astronaut
  • SUUMIMINE
  • timeToZoom
  • timeToOpenPopupAfterZoom
  • timeToUpdatePopupAfterZoom
  • popupContentHello
  • popupContentGatsby
  • markerRef

Järgige koos pühendumisega.

Jõuluvana leidmine

Nüüd, kui oleme heas kohas, määrime käed ja otsime üles jõuluvana. Selleks kasutame Google'i mitteametlikku, dokumentideta API-d. See tähendab, et on võimalik, et see API pole saadaval järgmisel päeval pärast selle avaldamist, kuid olgem optimistlikud.

Lisaks näitab see kirjutamise ajal veel eelmise aasta sihtkohti, nii et mida me siin tegelikult visualiseerime, on jõuluvana eelmise aasta marsruut, kuigi loodetavasti see taastub 24. päeval ja me oleme kõik rõõmsad!

Enne jõuluvana saamist lisame kõigepealt oma mapEffectfunktsiooni juurde rea :

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

See takistab ülejäänud meie koodi käitamist juhul, kui meie kaart pole veel valmis. mapEffectFunktsioon ise, kui saad näha Mapkomponent, jookseb sees astme useEffectläbimist Väide, refet kaardil, mis võimaldab meil käivitada mõned koodi pärast meie komponent muudab.

Nii et kui see joon on olemas, toogem nüüd oma mapEffectfunktsiooni sisse jõuluvana marsruut :

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); }

Jaotame selle:

  • Haarame jõuluvana teekonna läbi API lõpp-punkti
  • Kui tema marsruut on käes, haarame vastuse JSON-vormingus, et sellega oleks lihtsam töötada
  • See kõik on pakitud proovimisse / püüdmisse, et saaksime kõigi reageerimisvigadega turvaliselt hakkama saada
  • Lõpuks logselgitame praegu oma vastust

Nüüd on meil jõuluvana ja tema marsruut, mis tähendab, et näeme kõiki tema marsruudil olevaid sihtkohti. Kui pisut vastust kuhjata, näete mõnda lõbusat asja, näiteks seda, kui palju kinke igasse asukohta toimetati, ja ilmateadet!

Järgige koos pühendumisega.

Pange nõel tema asukohta

Leidsime jõuluvana! ? Nüüd paneme ta kaardile.

Meie eesmärkidel peame leidma jõuluvana laius- ja pikkuskraadi. Probleem on selles, et me ei saa seda täpset väärtust kusagil määratletud, vaid saame lihtsalt tema sihtkohad.

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

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

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

Kas soovite lugeda mõnda muud minu artiklit? Vaadake minu ajaveebi: //www.colbyfayock.com/2019/12/create-your-own-santa-tracker-with-gatsby-and-react-leaflet/