Place a Circle shape and show toast if clicked

- Posted in Markers by

If user clicks a circle, show a toast message.

1️⃣ Declare variables for a circle. Ensure that the clickable property is set to true.

1
2
3
    val circles = CircleOptions()
        .radius(10.0) 
        .clickable(true)   


2️⃣ Place the circle on the map, and add a tag to identify each placement.

1
 mMap.addCircle(circles.center(LatLng(25.16828, 121.44430))).tag = "haha"


3️⃣ Initialize setOnCircleClickListener to listen for user clicks, then show a toast message if the clicked circle matches the tag.

      mMap.setOnCircleClickListener {

          if (it.tag == "haha") {

              Toast.makeText(
                  applicationContext,
                  "haha message haha",
                  Toast.LENGTH_SHORT
              ).show()
          }
          else {
              Toast.makeText(
                  applicationContext,
                  "This is a test message",
                  Toast.LENGTH_SHORT
              ).show()
          }
      }

Place Ground Overlay and show toast if clicked

- Posted in Markers by

If user clicks a ground overlay, show a toast message.

1️⃣ Declare variables for a ground overlay to be placed on the map. Ensure that the clickable property is set to true.

    val mGOLatLng = LatLng(25.12299, 121.46196)
    val mGOMapOpt = GroundOverlayOptions()
        .image(BitmapDescriptorFactory.fromResource(R.drawable.SampleImage))
        .position(mGOLatLng, 100f)
        .clickable(true)


2️⃣ Place the ground overlay on the map, and add a tag to identify each placement.

    mMap.addGroundOverlay(mGOMapOpt)?.tag = "haha"


3️⃣ Initialize setOnGroundOverlayClickListener to listen for user clicks, then show a toast message if the clicked overlay matches the tag.

      mMap.setOnGroundOverlayClickListener {

       if (it.tag == "haha") {

           Toast.makeText(
               applicationContext,
               "This is a haha message",
               Toast.LENGTH_SHORT
           ).show()
       }
    }

Function to convert a vector asset to bitmap

- Posted in Markers by

Function to convert a vector asset to bitmap

1️⃣ First, add the giveMeBitmapDescriptor function:

private fun giveMeBitmapDescriptor(
    context: Context,
    iconPrm: Int
): BitmapDescriptor? {
    val background = ContextCompat.getDrawable(context, iconPrm)
    background!!.setBounds(0, 0, background.intrinsicWidth, background.intrinsicHeight)
    val bitmap = Bitmap.createBitmap(
        background.intrinsicWidth,
        background.intrinsicHeight,
        Bitmap.Config.ARGB_8888
    )
    val canvas = Canvas(bitmap)
    background.draw(canvas)
    val r = Rect()
    canvas.getClipBounds(r)
    val cHeight: Int = r.height()
    val cWidth: Int = r.width()
    val paint = Paint()
    paint.setTextAlign(Paint.Align.LEFT)
    paint.getTextBounds("text 1234567890", 0, "text 0002".length, r)
    val x: Float = cWidth / 2f - r.width() / 2f - r.left
    val y: Float = cHeight / 2f + r.height() / 2f - r.bottom
    canvas.drawText("sample text", x, y, paint)
    return BitmapDescriptorFactory.fromBitmap(bitmap)
}



2️⃣ Then set marker options as usual, but use the giveMeBitmapDescriptor to declare the icon:

    val markerOptionSVG = MarkerOptions()
        .position(LatLng(25.16828, 121.44430))
        .title("test")
        .snippet("sLcl2")
        .icon(giveMeBitmapDescriptor(this,R.drawable.SampleVectorImage))

    mMap.addMarker(markerOptionSVG)


Source:
[1] https://stackoverflow.com/questions/17837510/map-markers-with-text-in-google-maps-android-api-v2

Add a marker in Taipei

- Posted in Location by

Add a marker in Taipei

val taipei = LatLng(25.105497, 121.597366)
mMap.addMarker(
    MarkerOptions()
      .position(taipei)
      .title("Where do you want to go?")
      .icon(BitmapDescriptorFactory.fromResource(R.drawable.SampleImage))
)

Add a circle on the map

- Posted in Markers by

Add a circle on the map.

val circle: Circle = mMap.addCircle(
    CircleOptions()
        .center(LatLng(25.105497, 121.597366))
        .radius(10.0)
        .strokeColor(Color.RED)
        .fillColor(Color.BLUE)
        .clickable(true);
)

Center map to current location

- Posted in Location by

Query location manager for the user's 'last known location', then store the data as variables. Use retrieved data to move view to the 'last known location'.

    val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
    val criteria = Criteria()
    val provider = locationManager.getBestProvider(criteria, true)
    val location: Location? = 
        try { locationManager.getLastKnownLocation(provider!!) } 
        catch (e: NullPointerException) { null }

    if (location != null) {
        val latitude = location.latitude
        val longitude = location.longitude
        val coordinate = LatLng(latitude, longitude)
        val yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 19f)
        mMap.animateCamera(yourLocation)
    }

To ensure that the zoom animation triggers on load, place this code after you've added markers, or just ensure that this is the last code inside the onMapReady block.

Sample logic flow for Android location permissions

- Posted in Permissions by

Sample of kotlin code checking if user has already granted permission to access the user's current location data.

// 1️⃣ Check first if users have given permission.

private fun isPermissionGranted() : Boolean {
   return ContextCompat.checkSelfPermission(
        this,
       Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
}

// 2️⃣ If users have given permission, enable the location data layer.
//    If not, prompt user to grant permission. 

private fun enableMyLocation() {
    if (isPermissionGranted()) {
        map.isMyLocationEnabled = true
    }
    else {
        ActivityCompat.requestPermissions(
            this,
            arrayOf<String>(Manifest.permission.ACCESS_FINE_LOCATION),
            REQUEST_LOCATION_PERMISSION
        )
    }
}

// 3️⃣ Callback for the result from requesting permissions.
//    This method is invoked for every call on 
//    requestPermissions(android.app.Activity, String[], int).

override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String>,
    grantResults: IntArray) {
    // Check if location permissions are granted  
    // and if so enable the location data layer.
    if (requestCode == REQUEST_LOCATION_PERMISSION) {
        if (grantResults.contains(PackageManager.PERMISSION_GRANTED)) {
            enableMyLocation()
        }
    }
}

  To trigger the check, call the enableMyLocation() function inside the onMapReady block.

Code for new Map activity project

- Posted in Default by

This is the generated code for the default sample Map activity.

package com.---PROJECT-NAME---

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

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.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.---PROJECT-NAME---.databinding.ActivityMapsBinding

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap
private lateinit var binding: ActivityMapsBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    binding = ActivityMapsBinding.inflate(layoutInflater)
    setContentView(binding.root)

    // 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)
}

/**
 * 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

    // Add a marker in Sydney and move the camera
    val sydney = LatLng(-34.0, 151.0)
    mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
 }
}

Basic permission snippet for Google Maps

- Posted in Permissions by

A simple kotlin snippet to insert if you want to trigger the Android location permission dialog in mobile. The "Toast" part is optional.

        if (ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED
    ) {


        val text = "No permissions detected!"
        val duration = Toast.LENGTH_SHORT
        val toast = Toast.makeText(applicationContext, text, duration)
        toast.show()


        ActivityCompat.requestPermissions(
            this,
            arrayOf<String>(Manifest.permission.ACCESS_FINE_LOCATION),
            REQUEST_LOCATION_PERMISSION
        )


        return
    }

Remember to place this snippet immediately before the code/feature that requires permissions. For example:

mMap.isMyLocationEnabled = true