Android – MapView tutorial – Display current location on map in Android
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
- Create project in google cloud
- Enable Android SDK for google maps under Other solution -> Google Maps -> API
- Get your API key in API & Services -> Credential
- If API key is not already there create new API key
- Copy API Key
- 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) }
Share this content:
1 comment so far