Showing MapView on Android Emulator

313 Views Asked by At

I'm trying to show a MapView in an emulator in Android Studios, but when I try to run the activity, the MapView won't show up. I have tried to install the right SDKs from the SDK Manager and think I have the correct emulator to run the MapView. Please let me know what else I can try to have the MapView work. Thank you!

Pixel 5

enter image description here

AVD Manager

enter image description here

SDK Manager

enter image description here

activity_business_location.xml

<com.google.android.gms.maps.MapView
    android:id="@+id/businessLocationMapView"
    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_toBottomOf="@+id/toolbar"
    android:contentDescription="@string/business_location_map"/>

BusinessLocationActivity.kt

class BusinessLocationActivity : AppCompatActivity() {

    lateinit var jobService : JobService

    private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
    private lateinit var locationRequest: LocationRequest
    private lateinit var locationCallback: LocationCallback
    private var currentLocation: Location? = null

    private lateinit var placesService: PlacesService

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_business_location)

        jobService = intent.extras!!.get("jobService") as JobService
        placesService = PlacesService.create()

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
        setupLocationRequestAndCallback()
        getLocationUpdates()

        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowHomeEnabled(true)
        supportActionBar?.setTitle("Locate ${jobService.jobName}")
    }

    private fun setupLocationRequestAndCallback() {
        locationRequest = LocationRequest.create().apply {
            interval = 100
            fastestInterval = 50
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
            maxWaitTime= 10
        }

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                super.onLocationResult(locationResult)

                currentLocation = locationResult.lastLocation
                Log.e("Current Location", currentLocation.toString())

                getBusinessesNearby()

                // add this so location updates isn't running continuously
                // only need to run once to get current users location
                val removeTask = fusedLocationProviderClient.removeLocationUpdates(locationCallback)
                removeTask.addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        Log.d("BusinessLocation", "Location Callback removed.")
                    } else {
                        Log.d("BusinessLocation", "Failed to remove Location Callback.")
                    }
                }
            }
        }
    }

    private fun getLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }

        fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper()!!)
    }

    fun getBusinessesNearby() {
        val apiKey = getString(R.string.PLACES_API_KEY)

        placesService.nearbyPlaces(
            apiKey = apiKey,
            location = "${currentLocation?.latitude},${currentLocation?.longitude}",
            radiusInMeters = 80467,
            keyword = jobService.jobName
        ).enqueue(
            object : Callback<NearbyPlacesResponse> {
                override fun onFailure(call: Call<NearbyPlacesResponse>, t: Throwable) {
                    Log.e("BusinessLocation", "Failed to get nearby places", t)
                }

                override fun onResponse(
                    call: Call<NearbyPlacesResponse>,
                    response: Response<NearbyPlacesResponse>
                ) {
                    if (!response.isSuccessful) {
                        Log.e("BusinessLocation", "Failed to get nearby places")
                        return
                    }

                    val places = response.body()?.results ?: emptyList()
                    Log.e("Places Count: ", places.size.toString())

                    for (place in places) {
                        Log.e("Place: ", place.toString())
                    }
                }
            }
        )
    }

}

NearbyPlacesResponse.kt

data class NearbyPlacesResponse(
    @SerializedName("results") val results: List<Place>
)

PlacesService.kt

interface PlacesService {

    @GET("nearbysearch/json")
    fun nearbyPlaces(
        @Query("key") apiKey: String,
        @Query("location") location: String,
        @Query("radius") radiusInMeters: Int,
        @Query("keyword") keyword: String
    ): Call<NearbyPlacesResponse>

    companion object {
        private const val ROOT_URL = "https://maps.googleapis.com/maps/api/place/"

        fun create(): PlacesService {
            val logger = HttpLoggingInterceptor()
            logger.level = HttpLoggingInterceptor.Level.BODY
            val okHttpClient = OkHttpClient.Builder()
                .addInterceptor(logger)
                .build()
            val converterFactory = GsonConverterFactory.create()
            val retrofit = Retrofit.Builder()
                .baseUrl(ROOT_URL)
                .client(okHttpClient)
                .addConverterFactory(converterFactory)
                .build()
            return retrofit.create(PlacesService::class.java)
        }
    }
}
1

There are 1 best solutions below

0
GuilhermeMagro On

Did you follow the documentation? I think it is well explained how to config it. https://developers.google.com/maps/documentation/android-sdk/map

You need to add an Maps API Key to your project and do some other configs: https://developers.google.com/maps/documentation/android-sdk/config

Here is how you create your Maps API Key: https://developers.google.com/maps/documentation/android-sdk/get-api-key