How to display Popups on a Mapbox Map in React

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

This tutorial will be covering how to display popups on a Mapbox map in a React app with the react-map-gl library. Thisispart3(andthelastone)ofamulti-partReacttutorialonMapbox.Inpart1,wesimplyfocusondisplayingaMapboxmapandaddingageocodertolookupaddresses.Weevenmanagedtore-centerourmaptotheselectedaddress.Inpart2,welearnedhowtodisplaymarkersonaMapboxmap.Part3willbefocusingonpopupsandremovingmarkersfromamap.Let’sgetstarted! WanttobecomeaNext.jspro?IamputtingtogetheranonlinecourseonNext.js.Ifyouareinterested,signupandIwillkeepyouupdated.Keepmeupdated!Wewon'tsendyouspam.Unsubscribeatanytime.BuiltwithConvertKitStep1.CreateanddisplayaPopupcomponentOnceagain,wewillbeusingthereact-map-gllibrarywhichoffersanicePopupcomponent.SoIwillgoaheadandcreateaCustomPopupcomponenttodisplaytheaddressafterclickingonamarker.importReactMapGL,{Marker,Popup}from'react-map-gl'; constCustomPopup=({index,marker,closePopup})=>{ return(

{marker.name}

)};Again,thankstoreact-map-gl,wegetaPopupcomponentwhichtakeslat/long,butalsooffsetTop(meaning,inthiscase,Iwantthepopuptoappearontopofthemarker).Tomakeitwork,weaddneedanonClickonourmarkerscalledopenPopup.Thisfunctionwillsetwhichmarkerwasclickedthankstoitsuniqueindex.constCustomMarker=({index,marker,openPopup})=>{ return( openPopup(index)}> {index+1} )};Andbacktoourparentcomponent:constructor(props){ super(props); this.state={ ..., selectedIndex:null, ... }; } setSelectedMarker=(index)=>{ this.setState({selectedIndex:index}) } closePopup=()=>{ this.setSelectedMarker(null) }; openPopup=(index)=>{ this.setSelectedMarker(index) } render(){ return( ... { this.state.markers.map((marker,index)=>{ return( ) }) } ... ) }Torecapwhatjusthappened,we:addedaselectedIndextoourparentstateandasetSelectedMarkerfunctiontosettheselectedIndexcreatedaopenPopupandclosePopuptosettheindextoeithertheclickedmarkerornull.passedopenPopuptoourcustomMarkercomponentsothatwhenclicked,wecanlateropentherightpopupNowthatwehavesetourindex,let’salsodisplayapopupwhentheindexisnotnull.Soafterourmarkers,weadd:{ selectedIndex!==null&& }Weonlypasstherightmarker(todisplaythecorrectcontent),butalsoourclosePopupfunction.Step2.RemoveMarkersinaMapboxmapIpromisedatthebeginningthatIwouldshowyouhowtoremovemarkers,soherewego!Asadesigndecision,IhavedecidedtoaddmyRemovebuttoninthepopup.Sowhenauserclicksonamarker,apopupappearswiththeaddressandaremovebutton.Whenclicked,themarkerwilldisappearfromthemap.First,let’sstartbycreatingourremovefunction.Wewillusethemarker’sindextofilteritoutofourmarkersarray.WewillalsobesettingselectedIndextonullasthemarkerwilldisappearwithitspopup.Then,wewillbepassingthisfunctiontoourcustomPopup.remove=(index)=>{ this.setState(prevState=>({ markers:prevState.markers.filter((marker,i)=>index!==i), selectedIndex:null })) } ... render(){ return( ... { selectedIndex!==null&& } ... ); }Finally,let’saddaremovebuttontoourcustomPopupandusingourremovefunction:constCustomPopup=({index,marker,closePopup,remove})=>{ return(

{marker.name}

remove(index)}>Remove
)};Afairlystraightforwardwaytoeasilyremovemarkersonamap!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/That’sit!ThisisthefinalpartourthistutorialonMapboxandReact.Wehavelearnedhowto:displayamapaddageocodertolookupaddressesaddandremovemarkersdisplaypopupsforaspecificmarkerIhopethiswashelpful.FormoreMapboxtutorialsinReact:HowtodisplayaMapboxMapandGeocoderinReactThistutorialwillbecoveringhowtouseMapboxtodisplayamapandageocoderinReactwiththereact-map-glandreact-mapbox-gl-geocoderlibraries.MarieStarckMarieStarckHowtodisplayMarkersonaMapboxMapinReactThistutorialwillbecoveringhowtocreatemarkersonaMapboxmapforaReactapp.Wewillbeusingthereact-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



請為這篇文章評分?