Implementing Mapbox On React Native - GeekyAnts Tech Blog

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

An introduction on implementing Mapbox, a popular location data platform, on your React Native application. ImplementingMapboxOnReactNativeAnintroductiononimplementingMapbox,apopularlocationdataplatform,onyourReactNativeapplicationDeekshaMehta·Jul15,2021·7minreadListentothisarticleYourbrowserdoesnotsupporttheaudioelement.SPEED1XIntroduction Inthisarticle,wearegoingtolearnthebasicsofusingMapboxasatoolforintegratingmapsinReactNative.WhileGoogleMapsisprobablythemostfamousmappingsystem,therearevariousotherworthycontendersinthemarket.WhatmakesMapboxoneofthemostprominentplayersinthefieldisthefactthatitisalocationdataplatformthatpowersmapsandlocationservicesusedinmanypopularappsmakingitoneofthebestalternativesforGoogleMaps.Inthistutorial,wearegoingdelvestep-by-stepintocreatingcustommarkers,annotations,polylinesandpolygonsusingMapbox. Let'sGetStarted InordertouseMapbox,makesuretosignupforanaccounthere.Clickonthe"Startmappingforfree"buttonwhichwillnavigateyoutothesign-uppage.Butifyoualreadyhaveanaccount,youcanalternativelyloginwithyourusernameoremail. Aftersigningin,youcanseetheaccesstokeninthedashboardscreenwhichyouwillneedtogoahead.Refertothepicturebelow: ThenextstepistogoforwardistocreateaReactNativeprojectusingthestepsgivenhere. AddingMapboxMapsSDKforReactNative Now,wearegoingtosetupMapboxinourReactforwhichweneeda@react-native-mapbox-gl/mapsnpmpackagewhichwecaninstallusingthecommandgivenbelow: yarnadd@react-native-mapbox-gl/maps Alternatively,youcanalsousethefollowingcommand: npminstall@react-native-mapbox-gl/maps--save ForiOS,weneedtosetuptheMapboxmanuallyaspartoftheinstallationprocess.AddthesefollowinglinesinyouriOSpodfiletoachievethis: pre_installdo|installer| $RNMBGL.pre_install(installer) ...otherpreinstallhooks end post_installdo|installer| $RNMBGL.post_install(installer) ...otherpostinstallhooks end pod'react-native-mapbox-gl',:path=>'../node_modules/@react-native-mapbox-gl/maps' Don'tforgettorunpodinstallintheiOSdirectoryafterinstallationusingthefollowingcode: cdios&&podinstall&&cd.. Note:Formoreinformation,refertotheguidehere. Asweproceedtothenextstep,wewillhavetochangethecontentwithintheapp.jstoremovethedefaultcode.Usethefollowingcodetodothis: importReact,{useState}from"react"; import{View,StyleSheet,Text,Image}from"react-native"; importMapboxGLfrom"@react-native-mapbox-gl/maps"; Afterthis,wewillhavetosettheaccesstokenonMapboxGLastheMapboxdashboardalreadyhasthedefaulttoken.CopyandpastethecodegivenbelowinplaceoftheYOUR_MAPBOX_ACCESS_TOKEN: MapboxGL.setAccessToken("YOUR_MAPBOX_ACCESS_TOKEN"); Next,wearegoingtocreateApp.jscomponentusingfunctionalcomponentsasshownbelow: constApp=()=>{ } exportdefaultApp; AddingMapView,CameraandPointAnnotation MapViewprovidesanembeddablemapinterfacewhichyoucanusetodisplaymapinformationandtomanipulatethemapcontentsfromyourapplication.Youcanexecutethisbycenteringthemaponagivencoordinateandspecifyingthesizeoftheareayouwanttodisplayaswellasthestyleofthefeaturesofthemaptofityourapplication'susecase. Meanwhile,Cameraisthemap'sfieldofviewinmapsthatuseMapboxGL.Thecamera'sviewportisdeterminedbyseveralfactorslikeCenterwhichcoordinatesthecentreofthemapandZoomlevelwhichisanumberusedtodeterminehowclosetheviewportistothesurfaceofthemaps.Fordetailedinformation,referhere. PointAnnotationisusedtorenderthepointonamapusingcertainprops.Oneoftheprops,namelythecoordinateprop(const[coordinates]=useState([longitude,latitude]);),showsuswherethispointwouldbelocatedonthemap.Usethefollowingcodetogoahead: constApp=()=>{ const[coordinates]=useState([78.9629,20.5937]); return( ); } conststyles=StyleSheet.create({ page:{ flex:1, justifyContent:"center", alignItems:"center", backgroundColor:"#F5FCFF" }, container:{ height:'100%', width:'100%', backgroundColor:'blue', }, map:{ flex:1 } }); AddingCustomAnnotations YoucanalsoaddcustomannotationsinMapboxwhichyoucanusetorepresentdataofpoints,suchasrestaurantsinacity,busstopsalongaroute,orearthquakelocations.Let'screateafunctiontoshowourannotationpoint: constrenderAnnotations=()=>{ return( ); }; Next,wehavetocallthisfunctionintheMapViewcomponentasshownbelow: {renderAnnotations()} AddingCustomMarker MarkerViewprovidesasimplifiedwaytoaddmapmarkers.Youcanuseannotationstorepresentpointdata,suchasrestaurantsinacity,busstopsalongaroute,orearthquakelocations.Refertothecodebelow: {"Gujarat"} Thenextstepistoaddfollowingcodeinyourstylesheet: markerContainer:{ alignItems:"center", width:60, backgroundColor:"transparent", height:70, }, textContainer:{ backgroundColor:"white", borderRadius:10, flex:1, flexDirection:"row", alignItems:"center", }, text:{ textAlign:"center", paddingHorizontal:5, flex:1, }, Finally,addthepathofyourImagetagintothesourceattributesectiontocommenceaddingyourmarker. AddingPolylines Polylinesarelinesthatconnectstwoormorepointsonamap.ThemapprovidedbyMapboxdoesn'thaveaPolylinecomponentbydefault;but,wecanleverageothercomponentstogivesusthesameresultthatwederivefromthepolylineresultsonGoogleMaps.Toaddapolylineonthemap,wewouldbeusingtheShapeSourceandLineLayercomponentswhichareprovidedbyMapbox. ShapeSourceisamapcontentsourcethatsuppliesvectorshapeswhichcanbeshownonthemap.TheshapemaybeaURLoraGeoJSONobject. LineLayerisusedtoconfigurethevisualappearanceofpolyline. Tostartoff,definetherouteinwhichyouwanttoaddthepolyline,whoserouteshouldconditionallybeaGeoJSONobject.IamusinguseStatetostoretherouteinthisinstance.Refertothecodegivenbelowtogoahead. const[route,setRoute]=useState({ type:"FeatureCollection", features:[ { type:"Feature", properties:{}, geometry:{ type:"LineString", coordinates:[ [77.5946,12.9716], [80.2707,13.0827], ], }, }, ], }); Inthenextstep,addthefollowingcodeinsideMapboxGL.Camera: AddingPolygons Apolygonisageospatialfeaturedefinedbyconnectedpairsoflatitudeandlongitudecoordinatesthatformanareawithatleastthreesides.Youcanrepresentthedataofapolygonbyusingafilllayerorafillextrusionlayer.AFillLayerdefinesafilledpolygonwithanoptionalstrokedborder.Startoffbydefiningtherouteinwhichyouwanttohavepolygonandusethecodegivenbelow: const[polygon,setPolygon]=useState({ type:"Feature", geometry:{ type:"Polygon", coordinates:[ [ [72.685547,20.055931], [76.640625,21.207458], [76.904297,17.978733], [72.685547,20.055931], ], ], }, }); Inthenextstep,addthefollowingcodeinsidetheMapboxGL.MapViewcomponentforthedesiredresults: Results FollowingisapictorialrepresentationofwhatimplementingMapboxonyouriOSandAndroidapplicationwouldlooklikerespectively: WrappingUp Yeah,that'sawrap!Thankyousomuchforreading,IhopethisarticlehasbroadenedyourhorizonaboutMapboxanditsvariouscomponentswhilepromptingyoutogiveitashot.YoucanfindtheconsolidatedcodeinmyGitHubrepo: Clickheretoseethecode 44331 Sharethis



請為這篇文章評分?