Google maps
title: Google Maps Examples tags: - Maps chapter: Google Maps post_status: publish date: 2022-10-18 summary: A step by step Google Maps example.
A step by step Google Maps example.
GoogleMap Example
Kotlin Android Example Using GoogleMap, FusedLocationProviderClient and ClusterManager.
Below is a full android sample to demonstrate Google Maps concept.
Step 1. Dependencies
We need to add some dependencies in our app/build.gradle
file as shown below:
(a). build.gradle
Our app-level
build.gradle
.
We Prepare our dependencies as shown below. You may use later versions.
At the top of our app/build.gradle
we will apply the following 3 plugins:
- Our
com.android.application
plugin. - Our
kotlin-android
plugin. - Our
kotlin-android-extensions
plugin.
We then declare our app dependencies under the dependencies
closure. We will need the following 6 dependencies:
- Our
Kotlin-stdlib-jdk7
library. - Our
Appcompat
library. - Our
Core-ktx
library. - Our
Play-services-maps
library. - Our
Play-services-location
library. - Our
Android-maps-utils
library.
Here is our full app/build.gradle
:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.github.okwrtdsh.googlemapexample"
minSdkVersion 28
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'com.google.maps.android:android-maps-utils:0.5'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
Step 2. Our Android Manifest
We will need to look at our AndroidManifest.xml
.
(a). AndroidManifest.xml
Our
AndroidManifest
file.
Here we will add the following permission:
- Our
ACCESS_FINE_LOCATION
permission. - Our
ACCESS_COARSE_LOCATION
permission. - Our
ACCESS_BACKGROUND_LOCATION
permission.
Here is the full Android Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.github.okwrtdsh.googlemapexample">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 3. Design Layouts
In Android we design our UI interfaces using XML. So let's create the following layouts:
(a). activity_maps.xml
Our
activity_maps
layout.
Inside your /res/layout/
directory create an xml layout file named activity_maps.xml
and add a Fragment
as shown below:
fragment
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" />
Step 4. Write Code
Finally we need to write our code as follows:
(a). MapsActivity.kt
Our
MapsActivity
class.
Create a Kotlin file named MapsActivity.kt
.
We will then add imports from android SDK and other packages. Here are some of the imports we will use in this class:
Context
from theandroid.content
package.Location
from theandroid.location
package.Bundle
from theandroid.os
package.AppCompatActivity
from theandroidx.appcompat.app
package.
Next create a class that derives from ClusterItem
and add its contents as follows:
We will be overriding the following functions:
shouldRenderAsCluster(cluster: Cluster<MyItem>?): Boolean
.onCreate(savedInstanceState: Bundle?)
.onMapReady(googleMap: GoogleMap)
.
We will be creating the following methods:
setCurrentMarker(parameter)
- Our function will take aLatLng
object as a parameter.LatLng.toStr(): String
.
(a). Our LatLng.toStr()
function
Write the LatLng.toStr()
function as follows:
fun LatLng.toStr(): String {
val latDeg: Int = latitude.toInt()
val latMin: Int = ((latitude - latDeg.toDouble()) * 60.0).toInt()
val latSec: Int = ((latitude - latDeg.toDouble() - latMin.toDouble() / 60.0) * 3600.0).toInt()
val lngDeg: Int = longitude.toInt()
val lngMin: Int = ((longitude - lngDeg.toDouble()) * 60.0).toInt()
val lngSec: Int = ((longitude - lngDeg.toDouble() - lngMin.toDouble() / 60.0) * 3600.0).toInt()
return "lat: %02d°%02d′%02d″, lng: %03d°%02d′%02d″".format(
latDeg, latMin, latSec,
lngDeg, lngMin, lngSec
)
}
(b). Our setCurrentMarker()
function
Write the setCurrentMarker()
function as follows:
private fun setCurrentMarker(latlon: LatLng) {
currentMarker?.remove()
currentMarker = mMap.addMarker(
MarkerOptions()
.position(latlon)
.title("Your Location")
.snippet(latlon.toStr())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlon, 14f))
}
Here is the full code:
package replace_with_your_package_name
import android.content.Context
import android.location.Location
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.maps.android.clustering.Cluster
import com.google.maps.android.clustering.ClusterItem
import com.google.maps.android.clustering.ClusterManager
import com.google.maps.android.clustering.view.DefaultClusterRenderer
import kotlin.random.Random
class MyItem(position: LatLng, title: String, snippet: String) : ClusterItem {
private val mPosition = position
private val mTitle = title
private val mSnippet = snippet
override fun getSnippet() = mSnippet
override fun getPosition() = mPosition
override fun getTitle() = mTitle
}
class MyItemClusterRenderer(context: Context, map: GoogleMap, manager: ClusterManager<MyItem>) :
DefaultClusterRenderer<MyItem>(context, map, manager) {
override fun shouldRenderAsCluster(cluster: Cluster<MyItem>?): Boolean {
return cluster?.size ?: 0 >= 5
}
}
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
private var currentMarker: Marker? = null
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var mClusterManager: ClusterManager<MyItem>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
mClusterManager = ClusterManager<MyItem>(this, mMap).apply {
renderer = MyItemClusterRenderer(this@MapsActivity, mMap, this)
}
mMap.apply {
setOnCameraIdleListener(mClusterManager)
setOnMarkerClickListener(mClusterManager)
isMyLocationEnabled = true
uiSettings.apply {
isScrollGesturesEnabled = true
isZoomControlsEnabled = true
isZoomGesturesEnabled = true
isRotateGesturesEnabled = true
isZoomGesturesEnabled = true
isMapToolbarEnabled = true
isTiltGesturesEnabled = true
isCompassEnabled = true
isMyLocationButtonEnabled = true
}
}
// Add a marker in OsakaUniv and move the camera
var latlng = LatLng(34.822014, 135.524468)
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
if (location != null) {
latlng = LatLng(location.latitude, location.longitude)
setCurrentMarker(latlng)
}
}
setCurrentMarker(latlng)
val rnd = Random
(1..100).map {
val ll = LatLng(
rnd.nextDoubleNorm(latlng.latitude, 0.5),
rnd.nextDoubleNorm(latlng.longitude)
)
mClusterManager.addItem(
MyItem(
ll,
"point",
ll.toStr()
)
)
}
}
private fun setCurrentMarker(latlon: LatLng) {
currentMarker?.remove()
currentMarker = mMap.addMarker(
MarkerOptions()
.position(latlon)
.title("Your Location")
.snippet(latlon.toStr())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlon, 14f))
}
}
fun LatLng.toStr(): String {
val latDeg: Int = latitude.toInt()
val latMin: Int = ((latitude - latDeg.toDouble()) * 60.0).toInt()
val latSec: Int = ((latitude - latDeg.toDouble() - latMin.toDouble() / 60.0) * 3600.0).toInt()
val lngDeg: Int = longitude.toInt()
val lngMin: Int = ((longitude - lngDeg.toDouble()) * 60.0).toInt()
val lngSec: Int = ((longitude - lngDeg.toDouble() - lngMin.toDouble() / 60.0) * 3600.0).toInt()
return "lat: %02d°%02d′%02d″, lng: %03d°%02d′%02d″".format(
latDeg, latMin, latSec,
lngDeg, lngMin, lngSec
)
}
fun Random.nextDoubleNorm(mu: Double = 0.0, sigma: Double = 1.0): Double =
((1..12).map { nextDouble() }.sum() - 6.0) * sigma + mu
Reference
Download the code below:
No. | Link |
---|---|
1. | Download Full Code |
2. | Read more here. |
3. | Follow code author here. |
fevziomurtekin/custom-mapview
This is a customized Android library made using Google map.
A customized Android library made using Google map.
Here is the version code:
Here is the demoGIF:
To use it follow these steps:
Step 1: Install it
Install the project via gradle:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
.....
dependencies {
implementation 'com.github.fevziomurtekin:custom-mapview:0.1.2'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
}
}
Step 2: Enter your Google MapsKey
You must enter your Google Map key in Android Manifest.xml
:
Step 3: Write Code
Include it in the activity
class MainActivity : View() {
private var lists:MutableList<Place> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
/*Default place list adding*/
val anitkabir:Place = Place()
anitkabir.name="Anıtkabir"
anitkabir.placeType=PlaceType.HEART
anitkabir.content="Atatürk bir devri ..."
/*39.925276, 32.836955*/
anitkabir.latitude=39.925276
anitkabir.longitude=32.836955
lists.add(anitkabir)
this.addPlacesList(lists)
this.setMenuAnimation_time(350)
this.setSearchAnimation_time(350)
this.setFocus(LatLng(40.1122,29.061927))
this.setDefaultSearchError("error.")
}
}
Attributes
Here are the attributes:
PlaceList
menuAnimation_time
searchAnimation_time
defaultSearchError
focus
To add new places to the map, a list derived from the Place class must be submitted.
PlaceList
name
content
latitude
longitude
placeType
url
resource
phone
- If you leave the url and resource sections blank, we will use the icons given automatically.
Let us look at a full Example below:
Step 1. Our Android Manifest
We will need to look at our AndroidManifest.xml
.
(a). AndroidManifest.xml
Our
AndroidManifest
file.
We will be defining a meta-data
tag where we will specify the Google Maps key, which you must provide. Here is the full Android Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.fevziomurtekin.sample" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.NoActionBar" tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="@string/google_maps_key" />
<activity android:name=".MainActivity"
android:windowSoftInputMode="stateHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 2. Design Layouts
For this project let's create the following layouts:
(a). activity_main.xml
Our
activity_main
layout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Step 3. Write Code
Finally we need to write our code as follows:
(a). MainActivity.kt
Our
MainActivity
class.
Here is the full code:
package replace_with_your_package_name
import android.app.Activity
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.fevziomurtekin.custom_mapview.View
import com.fevziomurtekin.custom_mapview.data.Place
import com.fevziomurtekin.custom_mapview.util.PlaceType
import com.google.android.gms.maps.model.LatLng
class MainActivity : View() {
private var lists:MutableList<Place> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
/*Default place list adding*/
val school:Place = Place()
school.name="Uludag University"
school.placeType=PlaceType.SCHOOL
/*40.234583,28.8812533*/
school.latitude=40.234583
school.longitude=28.8812533
school.content="Aklın ve ..."
school.phone="(0224) 294 0000"
val uludag:Place = Place()
uludag.name="Uludağ National Park"
uludag.placeType=PlaceType.PARKING_AREA
uludag.url="https://cdn4.vectorstock.com/i/1000x1000/22/63/mountain-icons-on-white-background-vector-21032263.jpg"
uludag.content=""
/*40.112148,29.0715413*/
uludag.latitude=40.112148
uludag.longitude=29.0715413
val ulucamii:Place = Place()
ulucamii.name="Ulu Camii Mosque"
ulucamii.placeType=PlaceType.MOSQUE
ulucamii.resource=R.drawable.mosque
ulucamii.content="1395-1399 ... "
/*40.184151, 29.061927*/
ulucamii.latitude=40.18415
ulucamii.longitude=29.061927
val anitkabir:Place = Place()
anitkabir.name="Anıtkabir"
anitkabir.placeType=PlaceType.HEART
anitkabir.content="Atatürk..."
/*39.925276, 32.836955*/
anitkabir.latitude=39.925276
anitkabir.longitude=32.836955
lists.add(anitkabir)
lists.add(ulucamii)
lists.add(school)
lists.add(uludag)
this.addPlacesList(lists)
this.setMenuAnimation_time(350)
this.setSearchAnimation_time(350)
this.setFocus(LatLng(40.1122,29.061927))
this.setDefaultSearchError("error.")
}
}
Reference
Download the code below:
No. | Link |
---|---|
1. | Download Full Code |
2. | Read more here. |
3. | Follow code author here. |