How can I get current location on a SupportMapFragment?

Published

I’m having troubles of getting my current position coordinates using the GPS provider of android location system. I am a beginner in kotlin programming but I have already read a lot of tutorials and I didn’t find the answer.

Codes I’m using:

This is my Fragment:

class MapFragment : Fragment(), OnMapReadyCallback {

    private var _binding: FragmentMapBinding? = null
    private val binding get() = _binding!!
    private var storeList = mutableListOf<Store>()
    var gpsStatus: Boolean = false

    // TODO initialize
    private lateinit var currLocation: Location

    private val callback = OnMapReadyCallback { googleMap ->

        setMarkers(googleMap)
        val position = LatLng(storeList[0].location!!.latitude, storeList[0].location!!.longitude)
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 12f))

        // TODO current location
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {

        _binding = FragmentMapBinding.inflate(inflater, container, false)

        locationEnabled()

        if (gpsStatus) {
            Toast.makeText(context,"Location Services Is Enabled",Toast.LENGTH_SHORT).show()
        }
        else {
            Toast.makeText(context,"Location Services Is Not Enabled",Toast.LENGTH_SHORT).show()
        }

        initStores()
        return binding.root
    }

    override fun onMapReady(p0: GoogleMap) {
        // it's in the callback part
    }

    private fun initStores(){

        val db = Firebase.firestore
        db.collection("stores")
            .get()
            .addOnSuccessListener { documents ->
                for (document in documents) {
                    storeList.add(document.toObject())
                }
                val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
                mapFragment?.getMapAsync(callback)
            }
            .addOnFailureListener { exception ->
                Log.w("TAG", "Error getting documents: ", exception)
            }
    }

    private fun setMarkers(googleMap: GoogleMap){
        for (i in storeList){
            val position = LatLng(i.location!!.latitude, i.location!!.longitude)
            googleMap.addMarker(
                MarkerOptions().position(position).title(i.name).icon(
                BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)))
        }
    }

    private fun locationEnabled() {
        val locationManager = context?.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        gpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
    }
}

My xml file:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ProfileActivity" />

And my manifest file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="hu.bp.android.cafe">
    
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Cafe">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".ProfileActivity"
            android:exported="false"
            android:label="@string/title_activity_profile"
            android:theme="@style/Theme.AndroidFrei.NoActionBar" />
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="Cafe">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

GPS positioning is enabled but can you help me please and explain me in details what can i do now?

Source: Android Questions

Published
Categorized as android, fragment, google-maps, kotlin, location

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq