How to display Markers on a Mapbox Map in React

文章推薦指數: 80 %
投票人數:10人

We have our map and our geocoder. We can look up addresses and select one. Let's now display a marker on that particular address. Our react-map- ... Thisispart2ofamulti-partReacttutorialonMapbox.Inpart1,wesimplyfocusondisplayingamapandaddingageocodertolookupaddresses.Weevenmanagedtore-centerourmaptotheselectedaddress.Note:TolearnhowtodisplayaMapboxmapandageocoderinReact,don'thesitatetocheckitout!Whileverynice,amapdoesn’tquitefeelascompletewithoutmarkerstoshowuswhat’simportant.Solet’sgetstarted! WanttobecomeaNext.jspro?IamputtingtogetheranonlinecourseonNext.js.Ifyouareinterested,signupandIwillkeepyouupdated.Keepmeupdated!Wewon'tsendyouspam.Unsubscribeatanytime.BuiltwithConvertKitStep1.CreateanddisplayamarkercomponentWehaveourmapandourgeocoder.Wecanlookupaddressesandselectone.Let’snowdisplayamarkeronthatparticularaddress.Ourreact-map-gllibraryalsocomeswithahandyMarkercomponent.importReactMapGL,{Marker}from'react-map-gl';Thiscomponentwillallowustodisplayamarkerifwehaveselectedanaddress.Inourstate,wewilladdatempMarkersettonullandinouronSelectedfunction,wewillsettempMarkertothelatitude/longitudeitreturned.onSelected=(viewport,item)=>{ this.setState({ viewport, tempMarker:{ name:item.place_name, longitude:item.center[0], latitude:item.center[1] } }) }TheninsideourReactMapGLcomponent,wecandisplayourMarkercomponent:{tempMarker&& }OurMarkercomponenttakesalatitudeandalongitudealongwithitscontent.Youcanstyleyourmarkerhoweveryouwant.IamsimplygoingtouseanemptydivwithsomeCSStomakeitlooklikeanormalmarker.HereistheCSSIamusingtostylemymarker:Step2.AddMarkerstoyourMapboxmapThisisgood,buteverytimeIselectanaddress,themarkerchanges.WhatifIwanttosavemypreviousresults?CanIhavemorethanonemarker?Theanswerisyes.First,Iamgoingtoincludeanaddbuttonbesidemygeocoder.Whenauserlooksupanaddressandissatisfiedwiththeplacementofthemarker,itcanbemadepermanent.AddThen,inouraddfunction,wesimplyaddourtempMarkertoourmarkersarrayandsettempMarkerbacktonull.add=()=>{ var{tempMarker}=this.state this.setState(prevState=>({ markers:[...prevState.markers,tempMarker], tempMarker:null })) }Second,Iamgoingtodisplayamarkerforeveryaddresseswesaved.IcreatedaCustomMarkercomponentwhich1)willnumberourmarkerand2)notusethetemporary-markerclasssowecandifferentiateourpermanentvstemporarymarkersbasedoncolour.constCustomMarker=({index,marker})=>{ return( {index+1} )};Thenagain,insidetheReactMapGLcomponent,IwilluseCustomMarkertodisplayourmarkers.{ this.state.markers.map((marker,index)=>{ return( ) }) }Hereistheendresult:ResourcesThefollowinglibrariesareusefulforthistutorial:react-map-gl:https://www.npmjs.com/package/react-map-glreact-mapbox-gl-geocoder:https://www.npmjs.com/package/react-mapbox-gl-geocoderbootstrap:https://www.npmjs.com/package/bootstrapreactstrap:https://www.npmjs.com/package/reactstrapAndhereisthelinktoMapboxandit'sexamples:https://docs.mapbox.com/help/tutorials/ConclusionThisisitforPart2!Sofar,wehavedisplayedamap,addedageocoderandsavedaddressestobedisplayedasmarkers.Justtorecap,wehavelearnedhowtodisplayaMapboxmapandgeocoderinReact.Next,wewillgooverhowtocreatepopupsandremovemarkersonaMapboxmap.FormoreMapboxtutorialsinReact:HowtodisplayaMapboxMapandGeocoderinReactThistutorialwillbecoveringhowtouseMapboxtodisplayamapandageocoderinReactwiththereact-map-glandreact-mapbox-gl-geocoderlibraries.MarieStarckMarieStarckHowtodisplayPopupsonaMapboxMapinReactThistutorialwillbecoveringhowtodisplaypopupsonaMapboxmapinaReactappwiththereact-map-gllibrary.MarieStarckMarieStarck WanttobecomeaNext.jspro?IamputtingtogetheranonlinecourseaboutNext.js.Ifyouareinterested,signupandIwillkeepyouupdated!Keepmeupdated!Werespectyourprivacy.Unsubscribeatanytime.BuiltwithConvertKit AboutMarieStarck Iamafreelancefull-stackJavascriptsoftware(React,Next.js,Node.js).Iworkwithdesigners,entrepreneursandagenciesinneedoftechnicalhelp. Comments Showcomments ReadNext CloseSidebar ExploreSite AboutMarieStarck MarieStarckisfreelancefull-stacksoftwaredeveloper.Location-independentsince2017,shesplitshertimebetweenCanadaandFrance. RecentArticles February22,2021 AddGoogleAnalyticstoyourNext.jsapplicationin5easysteps February08,2021 HowtolocalizeyourNext.jsapplicationwithnext-translate December07,2020 ABeginner'sGuidetoDynamicRoutinginNext.js Tags TutorialReactNext.jsMapboxPerformancePrestaShopHerokuDevOps



請為這篇文章評分?