A component that holds the popup content that holds a reference; A declaration of the component adjacent to the element that hosts the mapbox-gl ...
Skiptocontent
TutorialBrianBancroftPosted:December7,2021mapboxMapboxGLJSmapbox-glmappingmapsReactweb
IfyouarecreatingaMapboxGLmapusingReact,theremaycomeatimewhenyouwanttobeabletotriggerReduxorotheractionsfromwithinsaidpopup.Ifyou’renotusingreact-map-gl,thisarticleisforyou.Ifyou’relookingforspoilers,seethiscodepenforafullimplementation.
WhatsetsthistutorialapartfromothersisthattheyusesetHTMLortheycreateasecondReactappinsidethefirstone,whichpreventsyoufromusingyourusualsetoftoolsformanagingstatefrominthepopup.Thistutorialdoesn’t.ItallowsyoutomanageandcontrolstateinsideaMapboxGLpopup.
Tomakethishappen,weneedthefollowingthings:
AcomponentthatholdsthepopupcontentthatholdsareferenceAdeclarationofthecomponentadjacenttotheelementthathoststhemapbox-glmapSomethingtoputintothepopup,andAtriggerforthepopuptooccur
Step1:CreatethePopupSurround
Thefirststepistocreateacomponentcalled.Thisiswhat’sgoingtosurroundthepopupcontent.
importReact,{useContext,useEffect,useRef}from"react";
import{mapContext}from"../context/mapContext";
importmapboxglfrom"mapbox-gl";
constPopupBase=({children,lngLat,...mapboxPopupProps})=>{
const{map}=useContext(mapContext);
constpopupRef=useRef();
useEffect(()=>{
constpopup=newmapboxgl.Popup({})
.setLngLat(lngLat)
.setDOMContent(popupRef.current)
.addTo(map);
returnpopup.remove;
},[children,lngLat]);
return(
{children}
);
};
exportdefaultPopup;
Noticethatwe’reusing“setDOMContent”.Youwanttousethismethodovertheusual“setHTML”.Withthis,we’regoingtoplacethisbythemapelement.
Step2:PutthePopupSurroundAdjacenttotheMap
Here,Iuseanactivestatevaluewhichholdsalnglatcoordinateasaproxyfor“shouldthepopupbevisible”.Therearemanywaystodothis,andthismaynotbethebest.Butitworks.
//Map.js-MapboxGLComponent
const[content,setContent]=useState(null);
const[popupLngLat,setPopupLngLat]=useState(null);
//...(restoftheReactcomponent)
return(
<>
{popupLngLat&&{content}}
(mapContainer.current=el)}style={styles}/>
>
);
WhenthepopupLngLatissetthefirsttime,thePopupBase-componentistriggered.Inthisexample,wedon’thaveafunctionwhichremovesthepopupLngLatvaluewhenthepopupcloses.Thisstillworks,butitmaymakemoresensetohaveactionsthatproperlyscrubsthestateonclose.
Steps3,4:AddtheContentintheTrigger
Forthispart,wehaveacomponentcalledPopupContent.Inthecodepenexample,it’sjustasetofreactelementsthathavesomearbitraryaction.Itcanbewhateveryouchooseittobe.NotethatIbuildthiscontentbasedonthearrayoffeaturesthatiscapturedbytheclickevent.Here,Isetthecontentstatehooktothecontent,aswellasthelnglatofthepopup.Asshownbeforeissufficienttotriggerthepopupinthemap.
map.on("click","geojson-layer",(e)=>{
constlabels=e.features.map((feature)=>(
));
setContent(labels);
setPopupLngLat(e.lngLat);
});
That’sallthereistoit.Atthispoint,youwillbeabletodoanythinginaMapboxpopupyoucoulddoelsewhereinyourReactapp.
FullImplementation
YoucanseeaworkingexampleofthisideaonCodeSandbox:
Inhere,Iusecontextinsteadofreduxtopropagatechangetothefooteroftheapplicationbasedonactionsausertakesinthepopup.Butitcanberedux.Itcanbeanythingyoudecideisworthdoing.
Talktous
IfyouarehavingproblemswithmappinginJavaScript,orifyouwanttomakeyourmapsmoreengaging,Letusknow.Sparkgeospendsafairamountoftimethinkingabouttheseproblems,andcanbeofservice.Ifyou’rehavingtroubleinthestepsbeforemakingyourmaps(especiallyinthedata-wranglingaspect),Sparkgeoalsohasyourback.Letushelpyoumakesenseofthismirrorworld.
Sharingoptions
Tutorial• GordonLogie
WildfiresandFloodDamage
Adata-backedresearchprojectexamininglinkagesbetweenthewildfiresandsubsequentflooddamagesthatoccurredinBC,2021.
Tutorial• DarrenWiens
AFreeOpenSourceFullMotionVideoWorkflow
FOSSFMVFTW:Atutorialonhowtoaccuratelymapvideoontoamap,usingopensourcesoftwareandstandards(STAC&STACAPI,Mapbox,MapLibre).
Tutorial• DarrenWiens
UsingMobileLiDARtoCreate3DModels
Asageospatialdeveloper,alotofwhatIdorevolvesarounddescribingthephysicalworldinadigitalway.Therearemanywaystodothis.Consider…
Needageospatialpartner?
Ourteamcomplementsorganizationslikeyours—byprovidingon-tapaccesstogeospatial,analytics,andmappingexpertise.
Let’stalk
Joinourteam?
We’realwayslookingforskilledtechnologiststohelpusbuildthefutureofgeospatial.Gotaminutetofindoutmoreaboutus?
WorkingHere
Sharingoptions
Thiswebsiteusescookiestoimproveyourexperienceandforanonymizedanalytics. AcceptPrivacy&CookiesPolicy
Close
PrivacyOverview
Thiswebsiteusescookiestoimproveyourexperiencewhileyounavigatethroughthewebsite.Outofthese,thecookiesthatarecategorizedasnecessaryarestoredonyourbrowserastheyareessentialfortheworkingofbasicfunctionalitiesofthewebsite.Wealsousethird-partycookiesthathelpusanalyzeandunderstandhowyouusethiswebsite.Thesecookieswillbestoredinyourbrowseronlywithyourconsent.Youalsohavetheoptiontoopt-outofthesecookies.Butoptingoutofsomeofthesecookiesmayaffectyourbrowsingexperience.
Necessary
Necessary
AlwaysEnabled
Necessarycookiesareabsolutelyessentialforthewebsitetofunctionproperly.Thiscategoryonlyincludescookiesthatensuresbasicfunctionalitiesandsecurityfeaturesofthewebsite.Thesecookiesdonotstoreanypersonalinformation.
Non-necessary
Non-necessary
Anycookiesthatmaynotbeparticularlynecessaryforthewebsitetofunctionandisusedspecificallytocollectuserpersonaldataviaanalytics,ads,otherembeddedcontentsaretermedasnon-necessarycookies.Itismandatorytoprocureuserconsentpriortorunningthesecookiesonyourwebsite.