Location

Blocks of code that applies to getting and setting user position.

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

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.