قالب وردپرس درنا توس
Home / Apple / Mapbook training for Android: Getting started

Mapbook training for Android: Getting started



Today, many apps have a placement feature. You use them all the time, whether you order food delivery, order a taxi, or even do laundry. Have you ever thought about building a local app yourself? You may think it is too complicated, or it may take too much time to build something close to some of the impressive apps with placement features built for Android. Well no longer! Thanks to the Mapbox SDK, you can build a cool Android app with location features. That's exactly what you want to do in this tutorial.

Using Mapbox Android SDK, you will build an app using map navigation called Where2Go . In this tutorial, you will learn how to:

  • Add the Map Library to project.
  • View the user's current location on the map.
  • Add a cursor to the map and navigate the turn of turns from the current location to the point where the cursor is on the map.

If you want to learn more about Mapbox, read more about it on the official website.

Getting Started

Before you learn about Mapbox, you need to download the starter and end projects using the link Download Materials at the top or bottom of this tutorial. Start Android Studio 3.3 or later, select Open an existing Android Studio project and then navigate to and select the start project folder.

 Open Project

When Gradle building load is completed, you can build and run the app to see what you have inside the startup project.

 Starting Project Running

The first thing you see after running the app is a blank screen and a floating action button. Not to move. But a little, when you implement the navigation with the Mapbox, you can navigate where you want! :]

Sign up for an account with a map box

The first thing to do before using the Mapbox SDK is to sign up for an account. So, once you have signed up, you get a access token . This token is the key you need to use the Mapbox SDK.

When you get to the Mapbox site, click Log in the button as pointed out by the red arrow. [19659002]   Sign up for Mapbox

You will be sent to another page that has a login form. You must click Sign up for the map box as shown in the red box.

 Register for chart box

Now you need to fill out the registration form and click Getting Started .

 Map box Enter form

Don't worry, registration is free. You can use the Mapbox SDK to build a small program. When your app becomes popular, they start charging you. : 19659000]  Pay as you go

Adding Mapbox Dependency

First open the file build.gradle (Module: app) and add compileOptions within android :

  compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

Secondly, add Mapbox and Google Play Service Location library dependencies within dependencies :

  implementation & # 39; com.mapbox. mapboxsdk: mapbox-android -navigation-ui: 0.26.0 & # 39;
implementation (& # 39; com.mapbox.mapboxsdk: mapbox-android-sdk: 6.8.1 & # 39;) {
exclude group: & # 39; group_name & # 39 ;, module: & # 39; module_name & # 39;
}
implementation & # 39; com.google.android.gms: play-services-location: 16.0.0 & # 39;

Finally open the file build.gradle (Project) and add the following lines inside allprojects directly below center () .

  mavenCentral ()
stomachs {url & # 39; https: //mapbox.bintray.com/mapbox'}

Click Synchronize Now to synchronize the project, which allows you to use the Mapbox library.

 Synchronize map box Android project

Working with MapBox

In this section, learn how to get a MapBox access token, get the user's current location, and display their location on the map.

Get a map box access token

Once you have signed up for an account with a map box, click on profile picture and select Account .

 Map box Select account

On the Account you will find a completely new access token, or You can use the default public token that you want to see in this tutorial.

Configure the map box to display the map

Open the file activity_main.xml . First, add xmlns: map box inside RelativeLayout .

  xmlns: mapbox = "http://schemas.android.com/apk/res-auto"

Add the tag to access map box attributes.

Then add the following code to display the map box.

  

Mapbook has different StyleUrl attributes, which you can use to change the overall map appearance. The one you want to use is mapbox_style_mapbox_streets .

Open the file AndroidManifest.xml and add the following permissions.

  

Add android.permission.ACCESS_FINE_LOCATION permission so that the Mapbox SDK can record your location and display it on the map. In the case of android.permission.FOREGROUND_SERVICE this is necessary when you want to start the swing of turn navigation.

Then opens the file MainActivity.kt adds the following code before the call to setContentView function:

  Mapbox.getInstance (this, "Your Map box access token")

When using Kotlin Android Extensions you can easily refer views of since you use id attributes defined in XML. To initialize the map box view, add this code under setContentView line:

  mapbox.onCreate (savedInstanceState)

Managing the Mapbox lifecycle is very important, so add the following code under the onCreate feature to complete the initialization and cleanup process:

  @SuppressWarnings ("MissingPermission")
override fun on Start () {
super.onStart ()
mapbox.onStart ()
}

override fun on Resume () {
super.onResume ()
mapbox.onResume ()
}

Override Fun at Pause () {
super.onPause ()
mapbox.onPause ()
}

Override fun at Stop () {
super.onStop ()
mapbox.onStop ()
}

Override fun on Destroy () {
super.onDestroy ()
mapbox.onDestroy ()
}

override fun onLowMemory () {
super.onLowMemory ()
mapbox.onLowMemory ()
}

override fun onSaveInstanceState (outState: Bundle?) {
super.onSaveInstanceState (outState)
if (outState! = null) {
mapbox.onSaveInstanceState (outState)
}
}

Mapbox has its own lifecycle methods for managing a Android openGL life cycle. You need to call these methods directly from the containing activity.

Note : You must add @SuppressWarnings ("MissingPermission") over onStart and the other methods, because these methods require you to implement permission management. You do not need this, however, because Mapbox handles it for you.

Build and run the app to see the result.

 Mapbook Android App Running

Discover the user's current location

Open the file MainActivity.kt and change the class declaration to implement the following interface.

  class MainActivity: AppCompatActivity (), PermissionsListener, LocationEngineListener, OnMapReadyCallback

You must use PermissionsListener to manage the local permission of devices running Android Marshmallow and later, while using LocationEngineListener to find the user's location. Finally, you need OnMapReadyCallback because this includes PermissionsListener and LocationEngineListener to start finding where the user is and displaying the location on the map. 19659002] Android Studio will now complain with errors telling you to add the necessary import. Mouse over the error and select Implement Members .

 Implementing android membership functions for the Mapbook project

Be sure to select all members and click OK .

 Select all members

Android Studio will automatically include the following code in MainActivity.kt .

  // 1
override fun onExplanationNeeded (permissionsToExplain: MutableList ?) {

}
// 2
override fun on Permission Result (provided: boolean) {

}
// 3
override fun onLocationChanged (location: location?) {

}
// 4
@SuppressWarnings ("MissingPermission")
Override fun at Connected () {

}
// 5
override fun onMapReady (mapboxMap: MapboxMap?) {

}
// 6
override fun on QuestPermissionsResult (requestCode: Int, permissions: Array  grantResults: IntArray) {

}

Let's go through this code together.

  1. onExplanationNeeded : Give an explanation to the user as to why you need the permission.
  2. onPermissionResult : Check if the permission was given or not by the user and how the app should handle this action.
  3. onLocationChanged : Monitor changes for user placements.
  4. onConnected : This is where the app is fully connected and can receive location updates.
  5. onMapReady : The map is clear and you can perform site-related activities.
  6. onRequestPermissionsResult : Override this extra method because it is the one who handles all permission related work.

Now let's add the required variables. You can add them to the top before onCreate feature.

  // 1
selection REQUEST_CHECK_SETTINGS = 1
var settingsClient: SettingsClient? = zero

// 2
Submit a map: MapboxMap
The Senate was permissionManager: PermissionsManager
where originLocation: Location? = zero

was locationEngine: LocationEngine? = zero
was locationComponent: LocationComponent? = zero

Let's go through the code above and get to know these variables.

  1. You use SettingsClient API to display a AlertDialog box where you want the user to turn on GPS to find the user's location.
  2. These variables are used for the map box and are all related to getting the user's location.

Then you need to create 4 methods. [19659002]   <code> <code> <code> <code> setCameraPosition </code> </li>
<li>  <code> <code> <code> initializeLocationComponent </li>
<li>  <code><br />
fun enableLocation () {</p><div><script async src=

}
// 2
@SuppressWarnings ("MissingPermission")
funny initializeLocationEngine () {

}

@SuppressWarnings ("MissingPermission")
funny initialization placement component () {

}

// 3
funny setCamera Position (location: location) {

}

Let's go through the code above.

  1. enableLocation : Allows you to enable location tracking to find the user's current location.
  2. initializeLocationEngine & initializeLocationComponent : These 2 functions are responsible for making the actual work of locating the user's location.
  3. setCameraPosition : This feature manages to zoom in on the user's location on the map.

Add the following code to the function onCreate .

  mapbox.getMapAsync (this)

This is a callback that will be triggered when the map map map is ready.

Next, you must initialize SettingsClient API .

  settingsClient = LocationServices.getSettingsClient (this)

Now you need to add the following code in onMapReady .

  // 1
map = mapboxMap ?: return
// 2
choice locationRequestBuilder = LocationSettingsRequest.Builder (). addLocationRequest (LocationRequest ()
.setPriority (LocationRequest.PRIORITY_HIGH_ACCURACY))
// 3
choice locationRequest = locationRequestBuilder? .build ()

setting client? .checkLocationSettings (locationRequest)?. run {
addOnSuccessListener {
enableLocation ()
}

addOnFailureListener {
choice statusCode = (as ApiException) .statusCode

if (statusCode == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
choice resolvableException = what? ResolvableApiException
resolvableException? .startResolutionForResult (this @ MainActivity, REQUEST_CHECK_SETTINGS)
}
}
}

The above code is all related to SettingsClient API so let's go through it step by step.

  1. First, initialize the map variable because you will be using it later.
  2. Initialize locationRequestBuilder and send the location request that the app will use.
  3. Finally, use locationRequest to build a location request. Then send it to settingsClient and add two types of listeners:
    • addOnSuccessListener : When the request is successful, you will call enableLocation to start location tracking.
    • addOnFailureListener : When the request fails, check to see the reason by looking at the exception status code. If the exception is LocationSettingsStatusCodes.RESOLUTION_REQUIRED the app should handle this exception by calling startResolutionForResult .

Then you must handle the exception result by overriding onActivityResult . Add the following code below onCreate .

  override fun onActivityResult (requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult (requestCode, resultCode, data)

if (requestCode == REQUEST_CHECK_SETTINGS) {
if (resultCode == Activity.RESULT_OK) {
enableLocation ()
} other if (resultCode == Activity.RESULT_CANCELED) {
finish()
}
}
}

First check if requestCode is correct and if resultCode is equal to Activity.RESULT_OK . Then, call the enableLocation method to start location tracking. [19659000] If resultCode is equal to Activity.RESULT_CANCELED the user has canceled the request and you call finish () to close the entire app.

] The reason you call finishes () is because the app needs the user to turn on GPS . If the user fails, the app doesn't work, so it's best to close the app.

Now is the time to see some progress, so build and run the app. is not turned on in your device, the app will ask you AlertDialog ] tells you to turn it on. When OK is pressed, the device GPS turns on. If you press NO, the THANKS button, the app closes.

If GPS in your device is ON, the app will not ask you AlertDialog .

Show the location on the map

Get now the user's current location and show it on the map. First, implement the enableLocation function by adding the following code inside it.

  if (PermissionsManager.are Localization TermsGranted (this)) {
initializeLocationComponent ()
initializeLocationEngine ()
} other {
permissionManager = PermissionsManager (this)
permissionManager.requestLocationPermissions (this)
}

Check if the site permit was granted. If it was, call initializerLocationComponent and initialize LocationEngine to begin locating the user. Otherwise, the app will ask the user for permission to access the site.

Change, change the function initializeLocationEngine by adding the following code.

  locationEngine = LocationEngineProvider (this) .obtainBestLocationEngineAvailable ()
location engine? .priority = LocationEnginePriority.HIGH_ACCURACY
location engine? .activate ()
location engine? .addLocationEngineListener (this)

choice lastLocation = locationEngine? .lastLocation
if (lastLocation! = null) {
originLocation = lastLocation
setCameraPosition (lastLocation)
} other {
location engine? .addLocationEngineListener (this)
}

In this code:

  • First you get the location.
  • Then put the priority high.
  • Then attach onLocationChanged & onConnected listeners so that the app can respond to any changes.
  • Finally, try to get the user's last location and send it to setCameraPosition method. If the user does not have a last location, call the location listeners again.

Now you need to include the following code in initialize LocationComponent .

  locationComponent = map.locationComponent
location component? .activateLocationComponent (this)
location component? .isLocationComponentEnabled = true
location component? .cameraMode = CameraMode.TRACKING
[19659000] In this code, you are: 

  • Initialize Location Component .
  • Enable and enable it to begin listening for the user's location.
  • Set cameraMode to CameraMode.TRACKING .

Change setCameraPosition to enable zooming into the user's location.

  map.animateCamera (CameraUpdateFactory.newLatLngZoom (LatLng (location.latitude,
location.longitude), 30.0))

Here you call animateCamera to move the camera map to the exact position based on location.latitude and location.longitude values, then enter the zoom value to 30.0 .

Next set up onExplanationNeeded onPermissionResult onLocationChanged and onConnected .

Add the following code in onExplanationNeeded .

  Toast.makeText (this, "This app needs placement permission to view your location on the map", Toast.LENGTH_LONG) .show ()

The app will now display a Toast message while asking the user to grant permission to access the site.

Add the following code in onPermissionResult . given) {
enableLocation ()
} other {
Toast.makeText (this, "User placement was not given", Toast.LENGTH_LONG) .show ()
finish()
}

Check if the site permission was given, and then start tracking tracking. If the permission was not given, the app will display a Toast message and close the app.

Then add the following code in onLocationChanged .

  place? run {
originLocation = this
setCameraPosition (this)
}

Pass the user's last location to the setCameraPosition method so that the map shows the current user's location all the time.

Add the following code in onConnected .

  location engine? .requestLocationUpdates ()

This will call locationEngine to track the user's location.

Now you need to add this code inside onRequestPermissionsResult .

  permissionManager.onRequestPermissionsResult (requestCode, permissions, grantResults)

permissionManager handles all permission-related work.

Now you need to change some more methods before you can run the app. First, you must include these code lines within onStart before mapbox.onStart () .

  if (PermissionsManager.areLocationGoomsGranted (this)) {
location engine? .requestLocationUpdates ()
location component? .onStart ()
}

Now the app will only retrieve the user's location if the site permission was given by the user.

Then you need to change onStop .

  location engine? .RemoveLocationUpdates ()
location component? .onStop ()

The app will stop retrieving the user's location updates when the onStop method is called.

Finally, you must add the following line to the method onDestroy .

  location engine? .Deactivate ()

This means that the app will disconnect from locationEngine and will no longer receive any location updates after the method onDestroy () is called. For information on MVP and life cycle, see this tutorial.

Now is the time to build and run the app to see the result.

 map box android project running with map loaded

Customize the map Appearance

Open the file MainActivity.kt and change the class header by adding MapboxMap .OnMapClickListener interface.

Now Android Studio will complain, tell you to implement the required method. When you choose to implement the method, make sure you select onMapClick and click OK .

After clicking the OK button, Android Studio will automatically add this new override method.

  override fun on MapClick (point: LatLng) {

}

First, change the enableLocation function by adding the following code.

  map.addOnMapClickListener (this)

You must add this because you want the map to respond to user cranes only when the user's location is visible on the map and because this class implements the interface

MapboxMap.OnMapClickListener .

Change the onMapClick method by adding the following code.

  map.addMarker (MarkerOptions () .position (point))

Here you add a cursor to a specific position by sending the point variable.

Now the app builds and runs to see the cursor. :]

 carton ogroid project with multiple android markers

It's cool to finally see a marker on the map, but it doesn't look right when you add more markers across the map, not right?

You can fix this by adding the following code in the onMapClick method.

  if (! Map.markers.isEmpty ()) {
map.clear ()
}

This removes any cursor before adding a new one to the map.

Build and run the app to see the result.

 carton ogroid project with a map marker

You can further customize the cursor by adding different cool things to it.

  map.addMarker (MarkerOptions (). SetTitle ("I am a marker:]") .position (point))

Here you add a string title that appears on the cursor.

You can also add an excerpt to the cursor.

  map.addMarker (MarkerOptions (). SetTitle ("I am a marker:]". SetSnippet ("This is an excerpt about this marker that will appear here") position (point))
[19659268] Now, using the Map Navigation API 

In this section, you learn how to use Map Box navigation api to add turn-by-turn navigation inside the app.

Direct User Between Places

Open the file MainActivity.kt and add the following code at the top before onCreate .

  Var navigationMapRoute: NavigationMapRoute? = zero
var currentRoute: DirectionsRoute? = zero

Here, you declare the required variables that you later use for navigation.

Next, you need to create a function called getRoute which takes two arguments, originPoint ] and endPoint . Be sure to import org.mapbox.Point class, instead of standard Android implementation.

  funny getRoute (originPoint: Point, endPoint: Point) {

}

You will use this feature later for user activity.

Now you need to change the function onMapClick by adding the following code.

  checkLocation ()
original location? .run {
choice startPoint = Point.fromLong (longitude, latitude)
choice endPoint = point.fromLangLat (point.longitude, point.latitude)

getRoute (startPoint, endPoint)
}

And create checkLocation function, which will attempt to set the field originLocation to the last known location, if no location exists.

  @SuppressLint ("MissingPermission")
private check check location () {
if (originLocation == null) {
map.locationComponent.lastKnownLocation? .run {
originLocation = this
}
}
}

In this code, start startPoint by sending originLocation latitude and longitude while initializing endPoint by sending point at the same. Finally, you will call getRoute by sending these two parameters: [start] and endPoint and endPoint .

Currently the ] getRoute feature does nothing. You can do it by adding the following code. [19659000] Make sure to import the classes retrofit2 when importing Callback Call and Answer types.

  NavigationRoute.builder this) // 1
.accessToken (Mapbox.getAccessToken () !!) // 2
.origin (originPoint) // 3
.destination (endpoint) // 4
.build () // 5
.getRoute (object: Callback  {// 6
override fun onFailure (ring: ring  t: Throwable) {

}

Override fun on Response (ring: Ring ,
Answer: Answer ) {

}
})

Let's go through this code block together.

  1. NavigationRoute.builder : Start navigation by first sending the current Context .
  2. accessToken : This causes Mapbox to access character
  3. origin : Enter the starting point for this navigation
  4. destination : End / destination point for this navigation
  5. build : Call this to build the navigation
  6. getRoute : Call this when you want to handle success and failure

Now you will handle onFailure the case by adding the following code.

  Log.d ("MainActivity", t.localizedMessage)

Here, the app will print a message in Logcat when an error occurs.

Finally, you must handle onResponse the case by adding the code below. [19659047] if (navigationMapRoute! = Null) {
navigationMapRoute? .updateRouteVisibilityTo (false)
} other {
navigationMapRoute = NavigationMapRoute (null, map box, map)
}

currentRoute = response.body ()?. routes ()? first ()
if (currentRoute! = null) {
navigationMapRoute? .addRoute (currentRoute)
}

The navigationMapRoute field is responsible for drawing a line on the map, from current location to destination.

You first check if navigation folderRoute is empty or not. If it is not empty, remove the route. Otherwise, you can initialize navigationMapRoute by sending three parameters:

  1. MapboxNavigation : This is a navigation example of MapboxNavigation that you resend in case you want to relocate during the navigation session. For this example, you will pass a null .
  2. map box : This is the map you want to draw the route on.
  3. MapboxMap : This will apply to the route.

Initialize currentRoute by accessing the reaction body and getting the first route from the routes () list.

] Finally, before adding a route, check if it is already a route, and then add the route to navigation folderRoute .

Now the app builds and runs to see the user's route on the map! :]

It's cool to see that the blue line on the map shows the user path, right? But it will be very cool if you can actually start navigation from a starting point until you reach the destination. Continue reading to find out how. Inside btnNavigate setOnClickListener method is where you want to add the following code.

  select navigationLauncherOptions = NavigationLauncherOptions.builder () // 1
.directionsRoute (currentRoute) // 2
.shouldSimulateRoute (true) // 3
.build()

NavigationLauncher.startNavigation (this, navigation loader) // 4

Let's go through this code.

  1. You create a constant navigation locksOptions that you then initialize with NavigationLauncherOptions . NavigationLauncherOptions is part of the map box classes that allow you to build the navigation pane.
  2. retningerRoute : Dette er den faktiske ruten du initierte tidligere.
  3. shouldSimulateRoute : Dette brukes til å simulere den faktiske sving ved svingnavigasjon. Du kan aktivere eller deaktivere dette slik du vil, og deretter ring bygge () .
  4. NavigationLauncher : Dette er en klasse som du kan bruke til å starte navigasjonen ved å sende to parametere: Kontekst og navigasjonslasteroppsett .

Nå bygger og kjører appen .

mapbox android app with turn by turn navigation

It feels awesome to finally see the navigation working, but what will happen when you tap on the navigation button without first adding any marker on the map ? The result is that the app will crash.

Here is how you can fix it. Open the MainActivity.kt file and add the following code to OnCreate.

btnNavigate.isEnabled = false

Here you disable the navigation button first in order to avoid starting the navigation before adding any marker on the map.

Now you can enable it inside the getRoute method, at the end of the onResponse block.

btnNavigate.isEnabled = true

You can now build and run the app. You can tap on the navigation button only when there’s a marker visible on the map. Otherwise, the button will be disabled.

Where to Go from Here?

You can download the completed project files by clicking on the Download Materials button at the top or bottom of this tutorial.

You can do even more with Mapbox Navigation APIfor example:

  1. Changing the language when you start turn by turn navigation.
  2. Changing the colors of the navigation UI.
  3. Setting up listeners to know whether the user is still in route or has reached the destination.

To learn more about Mapbox Navigation APItake a look at the documentation.

We hope you enjoyed this tutorial, and if you have any questions or comments, please join the forum discussion below!


Source link