For this example you would pass a null . mapbox : This is the map that you want to draw the route on top of. MapboxMap : This will apply the ...
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Shape
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
Group
raywenderlich.com
raywenderlich.com
Hidecontents
MapboxTutorialForAndroid:GettingStarted
GettingStarted
RegisterForanAccountwithMapbox
AddingtheMapboxDependency
WorkingwithMapBox
GettingaMapboxAccessToken
ConfiguringMapboxtoShowtheMap
DetecttheUser’sCurrentLocation
DisplayingtheLocationonMap
CustomizingtheMapAppearance
UsingtheMapboxNavigationAPI
DirecttheUserBetweenLocations
WheretoGofromHere?
Nowadays,manyappshavealocationfunction.Youusethemallthetime,whetheryou’reorderingfooddelivery,bookingacab,orevendoinglaundry.Haveyoueverthoughtaboutbuildingalocationappofyourown?Youmaythinkit’stoocomplicatedormaytaketoomuchtimetobuildsomethingclosetosomeoftheimpressiveappswithlocationfeaturesthathavebeenbuiltforAndroid.Wellnotanymore!ThankstotheMapboxSDK,youcanbuildacoolAndroidappwithlocationfeatures.That’sexactlywhatyou’lldointhistutorial.
UsingtheMapboxAndroidSDK,you’llbuildanappusingMapboxNavigationcalledWhere2Go.Inthistutorial,you’lllearnhowto:
AddtheMapboxlibrarytoproject.
Showtheuser’scurrentlocationonthemap.
Addamarkeronthemapandnavigateturnbyturnfromthecurrentlocationtothepointwherethemarkerisonthemap.
IfyouwanttolearnabitmoreaboutMapbox,youcanreadmoreaboutitattheofficialwebsite.
Prerequisites:ThistutorialassumesthatyouunderstandthebasicsofAndroiddevelopmentwithKotlin.Ifyou’renewtoAndroiddevelopment,pleasegothroughBeginningAndroidDevelopmentwithKotlintounderstandthebasics.Ifyou’renewtoKotlin,checkoutthisIntroductiontoKotlintutorial.
GettingStarted
BeforeyoulearnaboutMapbox,youhavetodownloadthestarterandfinalprojectsbyusingtheDownloadMaterialslinkatthetoporbottomofthistutorial.LaunchAndroidStudio3.3orlater,selecttheOpenanexistingAndroidStudioprojectoption,thennavigatetoandselectthestarterprojectfolder.
OnceGradlebuildloadingiscomplete,youcanbuildandruntheapptoseewhatyouhaveinsidethestarterproject.
Thefirstthingyou’llseeafterrunningtheappisanemptyscreenandafloatingactionbutton.Nottoomoving.Butinabit,whenyouimplementthenavigationusingMapbox,you’llbeabletonavigateanywhereyouwant!:]
RegisterForanAccountwithMapbox
ThefirstthingthatyouneedtodobeforeusingMapboxSDKistoregisterforanaccount.Then,onceyousuccessfullyregister,you’llgetanaccesstoken.ThistokenisthekeythatyouneedtobeabletousetheMapboxSDK.
OnceyouarriveattheMapboxwebsite,clickontheSigninbuttonaspointedoutbytheredarrow.
You’llbedirectedtoanotherpagewhichhasasigninform.YouneedtoclickonSignupforMapboxasshownintheredbox.
NowyouneedtofilloutthesignupformandclickGetstarted.
Don’tworry,theregistrationisfree.YoucanuseMapboxSDKtobuildasmallapplication.Onceyourappgetspopular,they’llstarttochargeyou.:]
AddingtheMapboxDependency
First,openthebuild.gradle(Module:app)fileandaddcompileOptionswithinandroid:
compileOptions{
sourceCompatibilityJavaVersion.VERSION_1_8
targetCompatibilityJavaVersion.VERSION_1_8
}
Second,addtheMapboxandGooglePlayServiceLocationlibrarydependencieswithindependencies:
implementation'com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.26.0'
implementation('com.mapbox.mapboxsdk:mapbox-android-sdk:6.8.1'){
excludegroup:'group_name',module:'module_name'
}
implementation'com.google.android.gms:play-services-location:16.0.0'
Finally,openthebuild.gradle(Project)file,andaddfollowinglinesinsidetheallprojectsrightunderthejcenter().
mavenCentral()
maven{url'https://mapbox.bintray.com/mapbox'}
ClickSyncnowtosynctheproject,whichallowsyoutousetheMapboxlibrary.
WorkingwithMapBox
Inthissection,you’lllearnhowtogetaMapBoxaccesstoken,gettheuser’scurrentlocation,andshowtheirlocationonthemap.
GettingaMapboxAccessToken
Onceyou’vesuccessfullyregisteredforanaccountwithMapbox,clickyourprofilepictureandchooseAccount.
InsidetheAccountpageiswhereyou’llcreateabrandnewaccesstoken,oryoucanusethedefaultpublictoken,asyou’llseeinthistutorial.
ConfiguringMapboxtoShowtheMap
Opentheactivity_main.xmlfile.First,youneedtoaddxmlns:mapboxinsideRelativeLayout.
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
AddthattagsoyoucanaccessMapboxattributes.
Next,addthefollowingcodetoshowtheMapboxmap.
MapboxhasdifferentStyleUrlattributes,whichyoucanusetochangetheoverallmapappearance.Theonethatyou’lluseismapbox_style_mapbox_streets.Thisstyleisaplainstylingofroadsandtransitnetworks.
NowopentheAndroidManifest.xmlfileandaddthefollowingpermissions.
Addtheandroid.permission.ACCESS_FINE_LOCATIONpermissionsothatMapboxSDKcandetectyourlocationandshowitonthemap.Asfortheandroid.permission.FOREGROUND_SERVICEpermission,thisisneededwhenyouwanttostarttheturnbyturnnavigation.
Next,opentheMainActivity.ktfile,addthefollowingcodebeforethecalltothesetContentViewfunction:
Mapbox.getInstance(this,"YourMapboxaccesstoken")
Bearinmind,youneedtoreplacethestringtextwiththeactualMapboxaccesstoken.
Sinceyou’llbeusingKotlinAndroidExtensions,youcaneasilyreferenceviewsbytheiridattributesdefinedintheXML.Toinitializethemapboxview,addthiscodebelowthesetContentViewline:
mapbox.onCreate(savedInstanceState)
HandlingtheMapboxlifecycleisreallyimportant,soaddthefollowingcodebelowtheonCreatefunctiontocompletetheinitializationandcleanupprocess:
@SuppressWarnings("MissingPermission")
overridefunonStart(){
super.onStart()
mapbox.onStart()
}
overridefunonResume(){
super.onResume()
mapbox.onResume()
}
overridefunonPause(){
super.onPause()
mapbox.onPause()
}
overridefunonStop(){
super.onStop()
mapbox.onStop()
}
overridefunonDestroy(){
super.onDestroy()
mapbox.onDestroy()
}
overridefunonLowMemory(){
super.onLowMemory()
mapbox.onLowMemory()
}
overridefunonSaveInstanceState(outState:Bundle?){
super.onSaveInstanceState(outState)
if(outState!=null){
mapbox.onSaveInstanceState(outState)
}
}
MapboxhasitsownlifecyclemethodsformanaginganAndroidopenGLlifecycle.Youmustcallthosemethodsdirectlyfromthecontainingactivity.
Note:Youneedtoadd@SuppressWarnings("MissingPermission")aboveonStartandtheothermethods,becausethesemethodsrequireyoutoimplementpermissionhandling.However,youdon’tneedthatherebecauseMapboxhandlesitforyou.
Buildandruntheapptoseetheresult.
DetecttheUser’sCurrentLocation
OpentheMainActivity.ktfileandchangetheclassdeclarationtomakeitimplementthefollowinginterfaces.
classMainActivity:AppCompatActivity(),PermissionsListener,LocationEngineListener,OnMapReadyCallback
YouneedtousePermissionsListenertohandlethelocationpermissionfordevicesrunningAndroidMarshmallowandlater,whileyouneedtouseLocationEngineListenertolocatetheuser’slocation.Finally,youneedOnMapReadyCallback,becausethiswhereyou’llincludePermissionsListenerandLocationEngineListenertobeginlocatingwheretheuserisandshowthatlocationonthemap.
AndroidStudiowillnowcomplainwitherrorstellingyoutoaddtherequiredimports.HoveryourmouseovertheerrorandchooseImplementmembers.
MakesuretoselectallthemembersandclickOK.
AndroidStudiowillautomaticallyincludethefollowingcodeinsideMainActivity.kt.
//1
overridefunonExplanationNeeded(permissionsToExplain:MutableList?){
}
//2
overridefunonPermissionResult(granted:Boolean){
}
//3
overridefunonLocationChanged(location:Location?){
}
//4
@SuppressWarnings("MissingPermission")
overridefunonConnected(){
}
//5
overridefunonMapReady(mapboxMap:MapboxMap?){
}
//6
overridefunonRequestPermissionsResult(requestCode:Int,permissions:Array,grantResults:IntArray){
}
Let’sgothroughthiscodetogether.
onExplanationNeeded:Provideanexplanationtotheuserforwhyyouneedthepermission.
onPermissionResult:Checkwhetherthepermissionwasgrantedornotbytheuser,andhowtheappwillhandlethataction.
onLocationChanged:Monitoruserlocationchanges.
onConnected:Thisiswheretheappisfullyconnectedandisabletoreceivelocationupdates.
onMapReady:Themapisready,andyoucanperformlocationrelatedactivities.
onRequestPermissionsResult:Overridethisextramethod,becauseit’stheonethathandlesallthepermissionsrelatedwork.
Nowlet’saddtherequiredvariables.Youcanaddthematthetop,beforetheonCreatefunction.
//1
valREQUEST_CHECK_SETTINGS=1
varsettingsClient:SettingsClient?=null
//2
lateinitvarmap:MapboxMap
lateinitvarpermissionManager:PermissionsManager
varoriginLocation:Location?=null
varlocationEngine:LocationEngine?=null
varlocationComponent:LocationComponent?=null
Let’sgothroughthecodeaboveandgettoknowthosevariables.
You’lluseSettingsClientAPItoshowanAlertDialogboxwhereyou’llasktheusertoturnonGPStolocatetheuser’slocation.
ThesevariablesareusedforMapbox,andareallrelatedtogettingtheuser’slocation.
Next,youneedtocreate4methods.
enableLocation
initializeLocationEngine
setCameraPosition
initializeLocationComponent
//1
funenableLocation(){
}
//2
@SuppressWarnings("MissingPermission")
funinitializeLocationEngine(){
}
@SuppressWarnings("MissingPermission")
funinitializeLocationComponent(){
}
//3
funsetCameraPosition(location:Location){
}
Let’sgothroughthecodeabove.
enableLocation:Thisiswhereyou’llenablelocationtrackingtolocatetheuser’scurrentlocation.
initializeLocationEngine&initializeLocationComponent:These2functionsareresponsiblefordoingtheactualworkoflocatingtheuser’slocation.
setCameraPosition:Thisfunctionhandleszoominginontheuser’slocationinthemap.
AddthefollowingcodeinsidetheonCreatefunction.
mapbox.getMapAsync(this)
ThisisacallbackwhichwillbetriggeredwhentheMapboxmapisready.
NextyouneedtoinitializeSettingsClientAPI.
settingsClient=LocationServices.getSettingsClient(this)
NowyouneedtoaddthefollowingcodeinsideonMapReady.
//1
map=mapboxMap?:return
//2
vallocationRequestBuilder=LocationSettingsRequest.Builder().addLocationRequest(LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY))
//3
vallocationRequest=locationRequestBuilder?.build()
settingsClient?.checkLocationSettings(locationRequest)?.run{
addOnSuccessListener{
enableLocation()
}
addOnFailureListener{
valstatusCode=(itasApiException).statusCode
if(statusCode==LocationSettingsStatusCodes.RESOLUTION_REQUIRED){
valresolvableException=itas?ResolvableApiException
resolvableException?.startResolutionForResult(this@MainActivity,REQUEST_CHECK_SETTINGS)
}
}
}
ThecodeaboveisallrelatedtoSettingsClientAPI,solet’sgothroughitstepbystep.
First,youinitializethemapvariable,becauseyou’llbeusingitlater.
InitializelocationRequestBuilderandpassthelocationrequestthattheappwilluse.
Finally,youuselocationRequesttobuildlocationrequest.ThenpassittosettingsClientandattachtwotypesoflisteners:
addOnSuccessListener:Whentherequestissuccessful,you’llcallenableLocationtoinitiatelocationtracking.
addOnFailureListener:Whentherequestfails,checktoseethereasonwhybylookingattheexceptionstatuscode.IftheexceptionisLocationSettingsStatusCodes.RESOLUTION_REQUIRED,thentheappshouldhandlethatexceptionbycallingstartResolutionForResult.
Next,youneedtohandletheexceptionresultbyoverridingonActivityResult.AddthefollowingcodebelowonCreate.
overridefunonActivityResult(requestCode:Int,resultCode:Int,data:Intent?){
super.onActivityResult(requestCode,resultCode,data)
if(requestCode==REQUEST_CHECK_SETTINGS){
if(resultCode==Activity.RESULT_OK){
enableLocation()
}elseif(resultCode==Activity.RESULT_CANCELED){
finish()
}
}
}
First,checkiftherequestCodeiscorrectandifresultCodeisequaltoActivity.RESULT_OK.Then,youcalltheenableLocationmethodtoinitiatelocationtracking.
IfresultCodeisequaltoActivity.RESULT_CANCELED,theuserhascancelledtherequestandyoucallfinish()toclosethewholeapp.
Thereasonyoucallfinish()isbecausetheappneedstheusertoturnONGPS.Iftheuserfailstodoso,theappwon’twork,soit’sbesttoclosetheapp.
Nowit’stimetoseesomeprogress,sobuildandruntheapp.:]
IfGPSisnotturnedONinyourdevice,theappwillpromptyouwiththeAlertDialogtellingyoutoturnitON.OnceyoutaponOK,thedeviceGPSwillturnON.OtherwiseifyoutapontheNO,THANKSbutton,theappwillclose.
IfGPSinyourdeviceisON,theappwillnotpromptyouwithAlertDialog.
DisplayingtheLocationonMap
Nowgettheuser’scurrentlocationandshowitonthemap.First,implementtheenableLocationfunctionbyaddingthefollowingcodeinsideit.
if(PermissionsManager.areLocationPermissionsGranted(this)){
initializeLocationComponent()
initializeLocationEngine()
}else{
permissionManager=PermissionsManager(this)
permissionManager.requestLocationPermissions(this)
}
Checktoseeifthelocationpermissionwasgranted.Ifitwas,callinitializeLocationComponentandinitializeLocationEnginetostartlocatingtheuser.Otherwise,theappwillasktheuserforpermissiontoaccessthelocation.
Next,modifytheinitializeLocationEnginefunctionbyaddingthefollowingcode.
locationEngine=LocationEngineProvider(this).obtainBestLocationEngineAvailable()
locationEngine?.priority=LocationEnginePriority.HIGH_ACCURACY
locationEngine?.activate()
locationEngine?.addLocationEngineListener(this)
vallastLocation=locationEngine?.lastLocation
if(lastLocation!=null){
originLocation=lastLocation
setCameraPosition(lastLocation)
}else{
locationEngine?.addLocationEngineListener(this)
}
Inthiscode:
First,yougetthelocation.
Next,setthepriorityashigh.
Then,attachtheonLocationChanged&onConnectedlistenerssothattheappcanrespondtoanychanges.
Finally,trytogettheuser’slastlocationandpassittosetCameraPositionmethod.Iftheuserdoesn’thavealastlocation,callthelocationlistenersagain.
NowyouneedtoincludethefollowingcodeinsideinitializeLocationComponent.
locationComponent=map.locationComponent
locationComponent?.activateLocationComponent(this)
locationComponent?.isLocationComponentEnabled=true
locationComponent?.cameraMode=CameraMode.TRACKING
Inthiscode,you:
InitializethelocationComponent.
Activateandenableittostartlisteningfortheuser’slocation.
SetcameraModetoCameraMode.TRACKING.
ModifysetCameraPositiontoenablezoomingintotheuser’slocation.
map.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(location.latitude,
location.longitude),30.0))
Here,youcallanimateCameratomovethecameramaptothatexactpositionbasedonlocation.latitudeandlocation.longitudevalues,thenyousetthezoomvalueto30.0.
Next,setuponExplanationNeeded,onPermissionResult,onLocationChangedandonConnected.
AddthefollowingcodeinsideonExplanationNeeded.
Toast.makeText(this,"Thisappneedslocationpermissiontobeabletoshowyourlocationonthemap",Toast.LENGTH_LONG).show()
TheappwillnowshowaToastmessagewhileaskingtheusertogivepermissiontoaccessthelocation.
AddthefollowingcodeinsideonPermissionResult.
if(granted){
enableLocation()
}else{
Toast.makeText(this,"Userlocationwasnotgranted",Toast.LENGTH_LONG).show()
finish()
}
Checkifthelocationpermissionwasgranted,theninitiatelocationtracking.Ifthepermissionwasn’tgranted,theappwillshowaToastmessageandclosetheapp.
Next,addthefollowingcodeinsideonLocationChanged.
location?.run{
originLocation=this
setCameraPosition(this)
}
Passtheuser’slatestlocationtothesetCameraPositionmethodsothemapwillshowthecurrentuser’slocationallthetime.
AddthefollowingcodeinsideonConnected.
locationEngine?.requestLocationUpdates()
ThiswillcalllocationEnginetotracktheuser’slocation.
NowyouneedtoaddthiscodeinsideonRequestPermissionsResult.
permissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults)
permissionManagerhandlesallthepermissionrelatedwork.
Nowyouneedtomodifyafewmoremethodsbeforeyoucanruntheapp.FirstyouneedtoincludetheselinesofcodeinsideonStartbeforemapbox.onStart().
if(PermissionsManager.areLocationPermissionsGranted(this)){
locationEngine?.requestLocationUpdates()
locationComponent?.onStart()
}
Now,theappwillretrievetheuser’slocationonlyifthelocationpermissionwasgrantedbytheuser.
Next,youneedtomodifyonStop.
locationEngine?.removeLocationUpdates()
locationComponent?.onStop()
Theappwillstopretrievingtheuser’slocationupdateswhentheonStopmethodiscalled.
Finally,youneedtoaddthefollowinglineintheonDestroymethod.
locationEngine?.deactivate()
ThismeansthattheappwilldisconnectfromlocationEngineandwillnolongerreceiveanylocationupdatesaftertheonDestroy()methodiscalled.ForinformationonMVPandlifecycle,seethistutorial.
Nowit’stimetobuildandruntheapptoseetheresult.
CustomizingtheMapAppearance
OpentheMainActivity.ktfile,andmodifytheclassheaderbyaddingtheMapboxMap.OnMapClickListenerinterface.
NowAndroidStudiowillcomplain,tellingyoutoimplementtherequiredmethod.Whenyouchoosetoimplementthemethod,makesureyouselectonMapClickandclickOK.
AfteryouclicktheOKbutton,AndroidStudiowillautomaticallyaddthisnewoverridemethod.
overridefunonMapClick(point:LatLng){
}
FirstyouneedtomodifytheenableLocationfunctionbyaddingthefollowingcode.
map.addOnMapClickListener(this)
Youneedtoaddthisbecauseyouwantthemaptorespondtousertapsonlywhentheuser’slocationisvisibleonthemap,andbecausethisclassimplementstheMapboxMap.OnMapClickListenerinterface.
ModifytheonMapClickmethodbyaddingthefollowingcode.
map.addMarker(MarkerOptions().position(point))
Hereyouaddamarkerataparticularpositionbypassingthepointvariable.
Nowbuildandruntheapptoseethemarker.:]
It’scooltofinallyseeamarkeronthemap,butitdoesn’tlookrightwhenaddingmultiplemarkersalloverthemap,right?
YoucanfixthisbyaddingthefollowingcodeinsidetheonMapClickmethod.
if(!map.markers.isEmpty()){
map.clear()
}
Thiswillremoveanymarkerbeforeaddinganewoneonthemap.
Buildandruntheapptoseetheresult.
Youcanfurthercustomizethemarkerbyaddingvariouscoolthingstoit.
map.addMarker(MarkerOptions().setTitle("I'mamarker:]").position(point))
Here,youaddastringtitlethatappearsonthemarker.Goaheadandruntheapptoseeitforyourself.
Youcanalsoaddasnippettothemarker.
map.addMarker(MarkerOptions().setTitle("I'mamarker:]").setSnippet("Thisisasnippetaboutthismarkerthatwillshowuphere").position(point))
Nowbuildandruntheapptoseethesnippet.
UsingtheMapboxNavigationAPI
Inthissection,you’lllearnhowtousetheMapboxnavigationapitoaddturnbyturnnavigationinsidetheapp.
DirecttheUserBetweenLocations
OpentheMainActivity.ktfile,andaddthefollowingcodeatthetop,beforeonCreate.
varnavigationMapRoute:NavigationMapRoute?=null
varcurrentRoute:DirectionsRoute?=null
Here,youdeclaretherequiredvariables,whichyou’lluselaterfornavigation.
Next,youneedtocreateafunctioncalledgetRoutethattakestwoarguments,originPointandendPoint.Makesuretoimporttheorg.mapbox.Pointclass,insteadofthedefaultAndroidimplementation.
fungetRoute(originPoint:Point,endPoint:Point){
}
Youwillusethisfunctionlaterforusernavigation.
Now,youneedtomodifytheonMapClickfunctionbyaddingthefollowingcode.
checkLocation()
originLocation?.run{
valstartPoint=Point.fromLngLat(longitude,latitude)
valendPoint=Point.fromLngLat(point.longitude,point.latitude)
getRoute(startPoint,endPoint)
}
AndcreatethecheckLocationfunction,whichwilltrytosettheoriginLocationfieldtothelastknownlocation,ifthereisn’tanylocationpresent.
@SuppressLint("MissingPermission")
privatefuncheckLocation(){
if(originLocation==null){
map.locationComponent.lastKnownLocation?.run{
originLocation=this
}
}
}
Inthiscode,youinitializestartPointbypassingoriginLocationthelongitudeandlatitude,whileyouinitializeendPointbypassingpointthesame.
Finally,you’llcallgetRoutebypassingthesetwoparameters:startPointandendPoint.
Atthemoment,thegetRoutefunctiondoesn’tdoanything.Youcanmakeitdosomethingbyaddingthefollowingcode.
Makesuretoimporttheretrofit2classeswhenimportingCallback,CallandResponsetypes.
NavigationRoute.builder(this)//1
.accessToken(Mapbox.getAccessToken()!!)//2
.origin(originPoint)//3
.destination(endPoint)//4
.build()//5
.getRoute(object:Callback{//6
overridefunonFailure(call:Call,t:Throwable){
}
overridefunonResponse(call:Call,
response:Response){
}
})
Let’sgothroughthatcodeblocktogether.
NavigationRoute.builder:StartthenavigationbyfirstpassingthecurrentContext.
accessToken:ThisgetsMapboxanaccesstoken
origin:Setthestartpointforthisnavigation
destination:Settheending/destinationpointforthisnavigation
build:Callthistobuildupthenavigation
getRoute:Callthiswhenyouwanttohandlesuccessandfailurecases
NowyouwanttohandletheonFailurecasebyaddingthefollowingcode.
Log.d("MainActivity",t.localizedMessage)
HeretheappwillprintamessageintheLogcatwhenafailurecasehappens.
Finally,youneedtohandletheonResponsecasebyaddingthecodebelow.
if(navigationMapRoute!=null){
navigationMapRoute?.updateRouteVisibilityTo(false)
}else{
navigationMapRoute=NavigationMapRoute(null,mapbox,map)
}
currentRoute=response.body()?.routes()?.first()
if(currentRoute!=null){
navigationMapRoute?.addRoute(currentRoute)
}
ThenavigationMapRoutefieldisresponsiblefordrawingalineonthemap,startingfromcurrentlocationtothedestination.
YoufirstcheckifnavigationMapRouteisemptyornot.Ifit’snotempty,youneedtoremovetheroute.Otherwise,initializenavigationMapRoutebypassingthreeparameters:
MapboxNavigation:ThisisanavigationinstanceofMapboxNavigationthatyoupassincaseifyouwanttorerouteduringthenavigationsession.Forthisexampleyouwouldpassanull.
mapbox:Thisisthemapthatyouwanttodrawtherouteontopof.
MapboxMap:Thiswillapplytheroute.
InitializecurrentRoutebyaccessingtheresponsebodyandgettingthefirstroutefromtheroutes()list.
Finally,beforeyouaddanyroute,checkwhetherthereisalreadyarouteandthenaddthatroutetonavigationMapRoute.
Nowbuildandruntheapptoseetheuser’srouteonthemap!:]
It’scooltoseethatbluelineonthemapshowingtheuserroute,right?Butit’llbereallycoolifyoucanactuallystartthenavigationfromastartingpointuntilyoureachthedestination.Continuereadingtofindouthow.:]
InsidebtnNavigate,thesetOnClickListenermethodiswhereyouwilladdthefollowingcode.
valnavigationLauncherOptions=NavigationLauncherOptions.builder()//1
.directionsRoute(currentRoute)//2
.shouldSimulateRoute(true)//3
.build()
NavigationLauncher.startNavigation(this,navigationLauncherOptions)//4
Let’sgothroughthatcode.
YoucreateaconstantnavigationLauncherOptions,whichyoutheninitializewithNavigationLauncherOptions.NavigationLauncherOptionsispartofMapbox’sclasses,whichallowyoutobuildthenavigationroute.
directionsRoute:Thisistheactualroutethatyouinitializedearlier.
shouldSimulateRoute:Thisisusedtosimulatetheactualturnbyturnnavigation.Youcanenableordisablethisasyoulike,andthencallbuild().
NavigationLauncher:Thisisaclassthatyoucanusetostartthenavigationbypassingtwoparameters:ContextandnavigationLauncherOptions.
Nowbuildandruntheapp.
Itfeelsawesometofinallyseethenavigationworking,butwhatwillhappenwhenyoutaponthenavigationbuttonwithoutfirstaddinganymarkeronthemap?Theresultisthattheappwillcrash.
Hereishowyoucanfixit.OpentheMainActivity.ktfileandaddthefollowingcodetoOnCreate.
btnNavigate.isEnabled=false
Hereyoudisablethenavigationbuttonfirstinordertoavoidstartingthenavigationbeforeaddinganymarkeronthemap.
NowyoucanenableitinsidethegetRoutemethod,attheendoftheonResponseblock.
btnNavigate.isEnabled=true
Youcannowbuildandruntheapp.Youcantaponthenavigationbuttononlywhenthere’samarkervisibleonthemap.Otherwise,thebuttonwillbedisabled.
WheretoGofromHere?
YoucandownloadthecompletedprojectfilesbyclickingontheDownloadMaterialsbuttonatthetoporbottomofthistutorial.
YoucandoevenmorewithMapboxNavigationAPI,forexample:
Changingthelanguagewhenyoustartturnbyturnnavigation.
ChangingthecolorsofthenavigationUI.
Settinguplistenerstoknowwhethertheuserisstillinrouteorhasreachedthedestination.
TolearnmoreaboutMapboxNavigationAPI,takealookatthedocumentation.
Wehopeyouenjoyedthistutorial,andifyouhaveanyquestionsorcomments,pleasejointheforumdiscussionbelow!
Maps&Location
Android&KotlinTutorials
DownloadMaterials
raywenderlich.comWeekly
Theraywenderlich.comnewsletteristheeasiestwaytostayup-to-dateoneverythingyouneedtoknowasamobiledeveloper.
Signupnow
Website
Getaweeklydigestofourtutorialsandcourses,andreceiveafreein-depthemailcourseasabonus!
Reviews
Allvideos.Allbooks.
Onelowprice.
Themobiledevelopmentworldmovesquickly—andyoudon’twanttogetleftbehind.LearniOS,Swift,Android,Kotlin,Dart,Flutterandmorewiththelargestandhighest-qualitycatalogofvideocoursesandbooksontheinternet.
Learnmore
Morelikethis
MarkComplete(AllChapters)
ClearProgress(AllChapters)
MarkComplete
ClearProgress
Completed
New
New
Don’tMissOurGoogleI/O2022Livecast–May11,9PMEST!
MultipleDomains
Announcements
May42022·Article(4mins)
JoinusforourFirstImpressionslivecasteventcoveringGoogleI/O2022highlights,opinionsfromourpanelofexpertsandmore!
May42022·Article(4mins)
Completed
JoinusforourFirstImpressionslivecasteventcoveringGoogleI/O2022highlights,opinionsfromourpanelofexpertsandmore!
May42022·Article(4mins)
Completed
MarkComplete(AllChapters)
ClearProgress(AllChapters)
MarkComplete
ClearProgress
Completed
New
New
FocusManagementinSwiftUI:GettingStarted
iOS&Swift
UserInterface
May32022·Article(25mins)
LearnhowtomanagefocusinSwiftUIbyimprovingtheuserexperienceforacheckoutform.
May32022·Article(25mins)
Completed
LearnhowtomanagefocusinSwiftUIbyimprovingtheuserexperienceforacheckoutform.
May32022·Article(25mins)
Completed
MarkComplete(AllChapters)
ClearProgress(AllChapters)
MarkComplete
ClearProgress
Completed
New
New
RunningaWebServeroniOSwithVapor
Server-SideSwift
SavingData/Persistence
Apr292022·Article(25mins)
WithVapor,youriOSappcanbeboththeclientandtheservertocontrolyourdata—orevenotherdevices.Thistutorialwillshowyouhowtogetstartedwithclient-servercommunicationinthesameprocess.
Apr292022·Article(25mins)
Completed
WithVapor,youriOSappcanbeboththeclientandtheservertocontrolyourdata—orevenotherdevices.Thistutorialwillshowyouhowtogetstartedwithclient-servercommunicationinthesameprocess.
Apr292022·Article(25mins)
Completed
MarkComplete(AllChapters)
ClearProgress(AllChapters)
MarkComplete
ClearProgress
Completed
New
New
BuildingDartAPIswithGoogleCloudRun
Flutter&Dart
OtherCoreAPIs
Apr282022·Article(30mins)
LearnhowtobuildbackendapplicationsusingDartandGoogleCloudRun.
Apr282022·Article(30mins)
Completed
LearnhowtobuildbackendapplicationsusingDartandGoogleCloudRun.
Apr282022·Article(30mins)
Completed
Contributors
AbdallaAli
SoftwareengineerwithapassionfordevelopingAndroidapps.LovetosharewhatIlearnwiththerestofthedeveloper...
Author
FilipBabić
Androiddeveloperwithahugepassionforlearning,teaching,anddiscussingtechnologies.Publicspeaker,mentor,video...
TechEditor
RyanDube
Ryanhasbeenwritingtechnology-basedarticlesonlinesince2007.AformerManagingEditorofMakeUseOf.com,heisawriter...
Editor
AdrianaKutenko
GraphicIllustratorwithaBachelor’sDegreeinFineArts.IamaperpetualperfectionseekerwithabigpassionforHistory...
Illustrator
JennBailey
Full-timecomputerscienceprofessorforAimsCommunityCollegeinColoradowhereshecreatedandteachescertificatesin...
Fpe
EricSoto
EricisAndroidTutorialTeamLeadandaProfessionalSoftwareEngineerandcertifiedAgile-ScrumMasterfocusingonAppleiOS...
TeamLead
Inthistutorial,you’lllearneverythingthereistosettingupasimpleGPSnavigationapp,usingMapBox,bybuildinganappcalledWhere2Go!
Comments
ShowComments.
Allvideos.Allbooks.Onelowprice.
Araywenderlich.comsubscriptionisthebestwaytolearnandmastermobiledevelopment—plansstartatjust$19.99/month!
LearniOS,Swift,Android,Kotlin,FlutterandDartdevelopmentandunlockourmassivecatalogof50+booksand4,000+videos.
Learnmore