August 13, 2021

Android – MapView tutorial – Display current location on map in Android

By lj007

Add MapView in xml

        <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Get google map key

  1. Create project in google cloud
  2. Enable Android SDK for google maps under Other solution -> Google Maps -> API
  3. Get your API key in API & Services -> Credential
  4. If API key is not already there create new API key
  5. Copy API Key
  6. Add in Manifest.xml file under application tag : <meta-data android:name=”com.google.android.geo.API_KEY” android:value=”YOUR_API_KEY”/>

Load map

        mapView.onCreate(savedInstanceState)
        mapView.getMapAsync(this)


        //Implement OnMapReadyCallback
        //this will override 

        override fun onMapReady(map: GoogleMap?) {
             mapView.onResume()
             //You can store map and use later
        }

Get Last known location or Get current location

Now we need to get our current location. Here is simple code which will give us device’s last known location. Below code will get last location.

       if (permissionGranted(Manifest.permission.ACCESS_FINE_LOCATION)) {
            LocationServices.getFusedLocationProviderClient(context!!)
                .lastLocation.addOnSuccessListener { location ->
                if(location != null)
                displayCurrentLocationOnMap(location)
            }
        }

Add marker on map

This is simple way to addMarker at particular position in android

   private fun displayCurrentLocationOnMap(location: Location) {
        if (googleMap == null) return //googleMap is previously stored from onMapReady
        val latLng = LatLng(location.latitude, location.longitude)
        val cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 12.6f)
        googleMap?.addMarker(MarkerOptions().position(latLng))
//        googleMap?.addMarker(MarkerOptions().position(latLng).draggable(true))
        googleMap?.moveCamera(cameraUpdate)
        getGeoInfo(latLng)
    }