Skip to content

Instantly share code, notes, and snippets.

@pavelpoley
Last active June 26, 2018 08:32
Show Gist options
  • Save pavelpoley/0253460cc21e2e779db61164332c7ee9 to your computer and use it in GitHub Desktop.
Save pavelpoley/0253460cc21e2e779db61164332c7ee9 to your computer and use it in GitHub Desktop.
Google MapView with Fragment
class MapsFragment : Fragment(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
private var mapView: MapView? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.fragment_maps, container, false)
mapView = v.mapView
mapView?.getMapAsync(this)
return v
}
/**
* 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))
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView?.onSaveInstanceState(outState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mapView?.onCreate(savedInstanceState)
}
override fun onResume() {
mapView?.onResume()
super.onResume()
}
override fun onStart() {
super.onStart()
mapView?.onStart()
}
override fun onPause() {
super.onPause()
mapView?.onPause()
}
override fun onStop() {
super.onStop()
mapView?.onStop()
}
override fun onDestroyView() {
super.onDestroyView()
mapView?.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView?.onLowMemory()
}
}
----- fragments_map.xml ----------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<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" />
</android.support.constraint.ConstraintLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment