How to place a location on Google Map

Here are few steps on how to add Google Map to your Kotlin/Android project, in this post, there are two things:

  • Show marker on Google Map
  • Get current location (Latitude & Longitude)

Show marker on Google Map

Step 1: Add dependencies in build.gradle:

compile 'com.google.android.gms:play-services:11.6.2'

Step 2: Set up Google Maps API Key in the AndroidManifest.xml. One example of the whole manifest file could be:

[gist https://gist.github.com/arkilis/f963e9fb3a7d0a00a4b7d8e424616dc7/]

Notice: Be careful about the <meta-data>’s location in the file. Error happened if it is outside &lt;application&gt;. You can obtain an API key from https://developers.google.com/maps/documentation/android-api/signup

Step 3: Setup UI in the resource file, the following example is using Fragment:

[gist https://gist.github.com/arkilis/f963e9fb3a7d0a00a4b7d8e424616dc7/]
Notice: Use com.google.android.gms.maps.SupportMapFragment.

Get current location (Latitude & Longitude)

Step 1: Add dependencies in build.gradle:

compile 'com.google.android.gms:play-services:11.6.2'
compile 'com.google.android.gms:play-services-location:10.+'

Step 2: Add necessary permissions and set up Google Maps API Key in the AndroidManifest.xml with the example above:


Step 3:

[gist https://gist.github.com/arkilis/7aef93cd50cf372d3a7c3ed5391e8fbf/]

First, the class is implemented an interface named OnMapReadyCallback, which will override a method named onMapReady

Second, then define a locationRequest used to handle the google map request, a variable named UPDATE_INTERVAL and FASTEST_INTERVAL to set up map update frequency.

Third, create a method named startLocationUpdates to initalize the mGoogleMap and setup locationRequest, including a Priority, Interval and FastInterval. Then create a location setting request builder and LocationCallback which actually return the updated information.

Fourth, since the android version 23 and above, the system will ask users for the permissions. We added a function to determine whether do we need extra permission or not.

You can have a look at the whole project at: https://github.com/arkilis/kotlin_google_maps

Reference

http://www.needone.app

About: arkilis


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.