Saturday, October 20, 2018

Getting Started With TomTom Maps SDK For Android Using Kotlin

Now is a great time to start using TomTom Maps SDK for your next Android Project. The new pricing structure that Google Maps recently implemented has developers looking for alternatives. TomTom offers developers an excellent Map SDK that is full of features, and easy to implement. Their Pay-As-You-Grow Plan includes free maps and traffic visualization, 2,500 free transactions per day for all APIs, 19 trillion location data points, customized support, and more. To see the full pricing structure and what is available visit TomTom For Developers Pricing.

The TomTom Maps SDK for Android comes as modules, Online Map, Online Search, and Online Routing, you can include one or all. The Online Map allows you to display and interact with maps using vector tiles, raster tiles, traffic incidents and patterns in your application. The Online Search allows you to search for an address, point of interest, or both. Additionally, it includes auto-completion and correction creating an awesome user experience. The Online Routing calculates routes with advanced parameters such as avoidance, eco routes, reachable range, time to leave, etc.

So now that I've convinced you to give TomTom a try let's get started building an app. In this tutorial, we will be displaying a map in a fragment within the main activity that places a marker at your current location.


Here is a breakdown of the steps we will complete for our project.

  1. Obtain A Map API Key From TomTom.
  2. Create A New Android Project With Kotlin Support.
  3. Edit The build.gradle Files And Android Manifest.
  4. Add A Map Fragment To The Layout File.
  5. Edit The Main Activity To Display The Map.
  6. Create A Function To Get Permissions And Display Location.


1. Obtain A Map API Key From TomTom.

To obtain the Map API Key go to TomTom For Developers and sign up for an account. Next, create a new app. Name it anything you like and check all the services you wish to include. For this project we are only using maps however, you can include others if you plan on expanding this project.

2. Create A New Android Project With Kotlin Support.

Now let's start building our app. Start a new Android Studio project and check the box that allows Kotlin support.



Next, choose target devices 19 and up. Then in the next screen choose to create an empty activity. In the last screen leave the default values unchanged and click finish.

3. Edit The build.gradle Files And The Android Manifest.

Project build.gradle

In the project's build.gradle file we add the TomTom repository as follows:
allprojects {
   repositories {
       google()
       jcenter()
       maven {
           url "https://maven.tomtom.com:8443/nexus/content/repositories/releases/"
      }
   }
}

Module build.gradle

Now to the module build.gradle file we add the dependencies for TomTom and for google play services location.
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.android.gms:play-services-location:11.8.0'
    api("com.tomtom.online:sdk-maps:2.250")
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Android Manifest 

In the AndroidManifest.xml file, we must declare that our application needs permission to ACCESS_FINE_LOCATION. Add the uses-permission element in your app manifest, as a child of the top-level element. Next, add the TomTom API key within the application tag of the manifest.





4. Add A MapFragment To The Layout File.

Now let's edit the layout file called activity_main.xml. It is located in the folder layout which is a subfolder of res. We will delete the textview that has been supplied as part of the project and add a MapFragment. Your file should now look like the following:

5. Edit The Main Activity To Display The Map.

Implement OnMapReadyCallback interface 

Open the MainActivity.kt class.  Add OnMapReadyCallback to this line of code:
class MainActivity : AppCompatActivity(), OnMapReadyCallback {

Now override the onMapReady method. Here we call our setUpMap function, we will write the code for the setUpMap function later on.

  override fun onMapReady(@NonNull tomtomMap: TomtomMap) {
        this.map = tomtomMap
        setUpMap()
    }

Add variables

Let's set up the variables for our map and location. We declare these as lateinit because they are a non-null type.
    private lateinit var map: TomtomMap
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var lastLocation: Location

Declare mapFragment

In the MainActivity onCreate method we get the mapFragment instance. Next, we call getAsyncMap on the supportMapFragment object to register the callback.

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val mapFragment = supportFragmentManager
                .findFragmentById(R.id.mapFragment) as MapFragment
        mapFragment.getAsyncMap(this)
    }

6. Create A Function To Get Permissions And Display Location.

Now we will create the function setUpMap that we called onMapReady. Here is where most of the work is done for the application. In addition to setting the permissions in the manifest we must ask for permissions at runtime. To obtain the device's location we use the fusedLocationClient and call the getLastLocation() method. We place a marker using the built-in SimpleMarkerBalloon. Finally, we set up the camera and zoom settings.
 private fun setUpMap() {
        if (ActivityCompat.checkSelfPermission(this,
                        android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE)
            return
        }
        map.isMyLocationEnabled = true
        fusedLocationClient.lastLocation.addOnSuccessListener(this) {
            location ->
            if (location != null){
                lastLocation = location
                val currentLatLng = LatLng(location.latitude, location.longitude)
                val balloon = SimpleMarkerBalloon("You are Here")
                map.addMarker(MarkerBuilder(currentLatLng).markerBalloon(balloon))
                map.centerOn(CameraPosition.builder(currentLatLng).zoom(7.0).build())
            }

        }
    }
In this tutorial, I have covered the basics of how to create an Android application that displays a map and the user's location using TomTom API. From this, we can add traffic, directions, routes, and further customize the map. You can find more information at https://developer.tomtom.com/maps-android-sdk/map-examples. The complete source code for this project is available at https://github.com/RealWorldApplications/TomTomKotlin/tree/MyLocationEnabled.