Mapbox GL JS is part of the Mapbox GL ecosystem, which also provides native SDKs for Android, iOS, macOS, Qt, and React Native apps.
React
UseMapboxGLJSinaReactApp
WrittenbyRohitGupta
Dec8·
5minread
>
Inthisarticle,IwillexplainhowwecanintegrateMapBoxAPIinaReactApplication.
Youcanreadmypreviousarticlehere:
CreateFormUIAddBackendLogicusingJSXMySQLCRUDOperationsusingExpressJS
Attheendofthisarticle,youwillhaveaworkingmapsapplication,whichwillprovideyoutheroutefromcurrentpositiontoanyotherlocation.
MapBoxGLJS
MapboxGLJSisaJavaScriptpackagethatallowsyoutocreatedynamic,editablevectormapsontheweb.IttakesMapboxStyleSpecification-compliantmapstyles,appliesthemtoMapboxVectorTileSpecification-compliantvectortiles,anddisplaysthemusingWebGL.
MapboxGLJSispartoftheMapboxGLecosystem,whichalsoprovidesnativeSDKsforAndroid,iOS,macOS,Qt,andReactNativeapps.Mapboxoffersbuildingpiecesforincorporatinglocationelementssuchasmaps,search,andnavigationintoanyexperienceyoudevelop.
MapboxGLJShasthefollowingusecases:
AnimatingandvisualizingspatialdataQueryingandfilteringmapfeaturesUsingaMapboxstyletoplaceyourdatabetweenlayersCustomclient-sidedataisdynamicallydisplayedandstyledonamap.Animationsandrepresentationsof3DdataProgrammaticallyaddingmarkersandpopupstomaps
ImportantLinks
Signforafreeaccount,here.Tohavealookatpre-createdexamples,visit.ToseeAPIReference,visit.
Installingrequiredpackages
WeneedtoinstalltheReactMapBoxGLJSpackage,usingthefollowing
npminstall--savereact-map-gl
AddingMapBoxAPI
MapBoxglJSprovidestwowaystouseit,SDKandAPI.IwillbeusingAPI.
Signintoyouraccount.Youwillseeatitleshowing“CreateawebmapwithMapboxGLJS”.
Afterthat,youwillgetanoptiontochooseifyouwanttoaddMapBoxAPIusingCDNorNPM.
IwillbeusingNPM,youcanuseCDNifyouwant.
Addthefollowingcodeinyourpublic/index.htmlfile.
Note:
Makesuretogetanaccesstoken.Ifhaveusedthedefaulttokenprovidedtoyouwhenyoucreateyouraccount.
Givenbelowisthestartercode,whichwecanusetointegrateMapBoxGL.
Map.css
GivenbelowisthestylesheetforMapBoxGLJS.
.map-container{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
}
.sidebar{
background-color:rgba(35,55,75,0.9);
color:#fff;
padding:6px12px;
font-family:monospace;
z-index:1;
position:absolute;
top:0;
left:0;
margin:12px;
border-radius:4px;
}
#instructions{
position:absolute;
margin:20px;
width:25%;
top:0;
bottom:20%;
padding:20px;
background-color:#fff;
overflow-y:scroll;
font-family:sans-serif;
}
Settinguptheproject
Youcaneithercreateanewprojectoraddthecodetoyouroldproject.
Addthefollowingcode,whichimportsallrequiredfiles.
importReact,{useRef,useEffect,useState}from'react';
importmapboxglfrom'mapbox-gl';
import'./component/Map.css'
Afterthat,wedeclarethefollowingvariablesusingReactHooks.
constmapContainer=useRef(null);//MapBoxContainer
constmap=useRef(null);//MapBoxrenderedelement
const[lng,setLng]=useState(77.378);//Longitude
const[lat,setLat]=useState(28.624);//Latitude
const[zoom,setZoom]=useState(12);//ZoomLevel
conststart=[lng,lat];//InitialDirections
WeuseanuseEffect()hooksotorendertheMapBoxAPIafterthesiteloads.Itwillrenderonceeverytimewereload.TolearnaboutReactuseEffect()hook,visit.
useEffect(()=>{
if(map.current)return;//initializemaponlyonce
map.current=newmapboxgl.Map({
container:mapContainer.current,
style:'mapbox://styles/mapbox/streets-v11',
center:[lng,lat],
zoom:zoom
});
map.current.on('move',()=>{
setLng(map.current.getCenter().lng.toFixed(4));
setLat(map.current.getCenter().lat.toFixed(4));
setZoom(map.current.getZoom().toFixed(2));
});
route();
},[map.current]);
WeinitializetheMapusingthemapboxgl.Map()WedefinethemapstyleasStreets-v11,youcanchooseanyofthestylefromMapBoxStyles.Wesetthestartpointasthecenterofthemap.Sothatwhenevermapisrendereditshowsthislocation.Wedeclaretheactiontobetakenwhenwemoveusingmap.current.on()setLng(),setLat()andsetZoom()isusedtochangethecenteraswhenthemapismoved.
locate()
locate()isusedtoaddanautolocatefeaturetothemap.Iwillbeusingittosettheinitialpositionwheneverfindingtheroute.
constlocate=()=>{
map.current.addControl(
newmapboxgl.GeolocateControl({
positionOptions:{
enableHighAccuracy:true,
},
//Whenactivethemapwillreceiveupdatestothedevice'slocationasitchanges.
trackUserLocation:true,
style:{
right:10,
top:10
},
position:'bottom-left',
//Drawanarrownexttothelocationdottoindicatewhichdirectionthedeviceisheading.
showUserHeading:true
})
);
}
Weusemapboxgl’sGeoLocationAPI.
WeneedtosettrackUserLocationastrue,tobeabletotrackuserlocation.IhavesetenableHighAccuracyastrue,soastogetacuratelocation.Setpositionas‘bottom-left’,soastopositionthelocationicononleftsidebottomcorner.
route()
Wecreateanarrowfunction‘route’.Thisfunctionisusedtofindandplottheoptimizedrouteonthemap.
constroute=()=>{
locate();
map.current.on('load',()=>{
//code
});
}
Wecalllocatetopositionthemaponyourcurrentlocation.
Afterthat,wecallanon()todefinetheactionstobetakenwhenweclickonthedestinationlocation.
Addthefollowingcodeunder‘route()’.
//Addstartingpointtothemap
map.current.addLayer({
id:'point',
type:'circle',
source:{
type:'geojson',
data:{
type:'FeatureCollection',
features:[{
type:'Feature',
properties:{},
geometry:{
type:'Point',
coordinates:start
}
}]
}
},
paint:{
'circle-radius':10,
'circle-color':'#3887be'
}
});
Intheabovecode,weplotaninitialpointonthemap,usingtheaddLayer().
map.current.on('click',(event)=>{
//code
getRoute(coords);
});
Wecreateanaction,tobetakenwheneverweclickonthemap.Weaddthefollowingcode,afterthat,wecallgetRoute()toplottheroutegraphically.
constcoords=Object.keys(event.lngLat).map((key)=>event.lngLat[key]);
constend={
type:'FeatureCollection',
features:[{
type:'Feature',
properties:{},
geometry:{
type:'Point',
coordinates:coords
}
}]
};
Intheabovecode,wedeclare‘coords’asanobjectwhichcontainsthelocationdata.
Wedeclare‘end’withdemodetails,whichwillbechangedbasedontheclickmadebytheuser.
if(map.current.getLayer('end')){
map.current.getSource('end').setData(end);
}else{
map.current.addLayer({
id:'end',
type:'circle',
source:{
type:'geojson',
data:{
type:'FeatureCollection',
features:[{
type:'Feature',
properties:{},
geometry:{
type:'Point',
coordinates:coords
}
}]
}
},
paint:{
'circle-radius':10,
'circle-color':'#f30'
}
});
}
Intheabovecode,iftheuserhasalreadyclickedonthescreen,getthecoordinates.Otherwise,makeaplotofthepointbasedontheclickmadebytheuser.
getRoute()
Wecreateanasynctocreateanoptimalroutebetweenthetwoandplotsontothemap.
asyncfunctiongetRoute(end){
constquery=awaitfetch(
`https://api.mapbox.com/directions/v5/mapbox/cycling/${start[0]},${start[1]};${end[0]},${end[1]}?steps=true&geometries=geojson&access_token=${mapboxgl.accessToken}`,
{method:'GET'}
);
constjson=awaitquery.json();
constdata=json.routes[0];
constroute=data.geometry.coordinates;
constgeojson={
type:'Feature',
properties:{},
geometry:{
type:'LineString',
coordinates:route
}
};
//code
}
Weusefetch()toconnect,makearequest,andgetaresponsefromtheMapBoxAPI.
Afterthat,webreaktheresponse,soastogettherequireddata,whichwillthenbeplottedontothemap.
//iftheroutealreadyexistsonthemap,we'llresetitusingsetData
if(map.current.getSource('route')){
map.current.getSource('route').setData(geojson);
}
//otherwise,we'llmakeanewrequest
else{
map.current.addLayer({
id:'route',
type:'line',
source:{
type:'geojson',
data:geojson
},
layout:{
'line-join':'round',
'line-cap':'round'
},
paint:{
'line-color':'#3887be',
'line-width':5,
'line-opacity':0.75
}
});
}
Intheabovecode,wecheckiftherouteexistsonuserclick.Iftherouteexists,weresettherouteandcreateanewroute.
//getthesidebarandaddtheinstructions
constinstructions=document.getElementById('instructions');
conststeps=data.legs[0].steps;
lettripInstructions='';
for(conststepofsteps){
tripInstructions+=`${step.maneuver.instruction}`;
}
instructions.innerHTML=`Tripduration:${Math.floor(
data.duration/60
)}min🚴
${tripInstructions}
`;
TheabovecoderenderstheUI,withthenavigationdetails,i.e.stepstobetakentoreachthedestination.
HTMLCode
Addthefollowingcodeunderreturntoaddthemapandroutecomponents.
Downloadthecompletecodefrombelow:
react_formDownload
Conclusion
Thanksforreading,hopeyougotanswerstosomeofyourquestionsandlearnedtocreateaReactbasedMapsapplicationtofindroutebetweentwolocations.
Visit Let’sReacttolearnmoreaboutReact.
2,193 views
MapBoxMapsReactReactJSXReactJs
WrittenbyRohitGupta
C#CornerMVPProgramDirector.IamanIntel®AIEdgeScholar,ML&CognitiveRoboticsEnthusiast,and2timesC#CornerMVP.IfeelthatbondingbetweenMachinesandHumanswillmakethisworldabetterplace.Iaspiretobethefirstpersontomakeageneral-purposehuman-likehumanoid.Iused"human"2timesbecausenotechnologycaneverhavewhatwecall"Insaniyat".
https://www.linkedin.com/in/rohit-gupta-04578471/
https://hindikijiwani.blogspot.com/
Profile
3
Share
Reply
0
Archives
May2022
April2022
March2022
February2022
January2022
December2021
November2021
October2021
July2021
April2021
March2021
February2021
January2021
December2020
November2020
Categories
LearnReact
React
ReactHowTo
ReactNews
ReactTutorial
Meta
Login
Entriesfeed
Commentsfeed
WordPress.org
BootStrapAccordionWithReact
ShivangiRajde
in
LearnReact,React,ReactTutorial
Mar8,2022
·
4minread
Package.jsonExplained
ShivangiRajde
in
LearnReact,React
Mar4,2022
·
5minread
Flutterv/sReactNative
ShivangiRajde
in
React
Mar2,2022
·
3minread
LeaveaReplyCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*
Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment.
Signin
Rememberme
Login
Forgotyourpassword?
Lostyourpassword?Pleaseenteryouremailaddress.Youwillreceivemailwithlinktosetnewpassword.
Resetpassword
Backtologin