'Jetpack compose with Google Place API

I am trying to use Place SDK with jetpack compose but I can not find any resource on how to implement this.

@Composable
fun PlaceSearchView() {
    // Initialize the SDK
    Places.initialize(applicationContext, "apiKey")

    
    val placesClient = Places.createClient(this)
}

The above code is based on what is available in the Documentation and I am getting the error

Unresolved reference: applicationContext

My question now: is there a dedicated approach to using google place API in Jetpack Compose?

'this' is not defined in this context



Solution 1:[1]

You can use this code to create an intent to launch autocomplete widget as an intent. The code is similar to this

@HiltViewModel
class MyViewModel @Inject constructor(private val myUseCase: MyUseCase, @ApplicationContext applicationContext: Context): ViewModel() {
    init {
        Places.initialize(applicationContext, "insert api key")
    }

    val field = listOf(Place.Field.NAME, Place.Field.LAT_LNG)

    }
@Composable
fun MyScreen(myViewModel: MyViewModel = hiltViewModel()) {
    val context = LocalContext.current
    val intent = Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, exploreViewModel.field).build(context)

    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
       
        if(it.resultCode == RESULT_OK){
            val place = Autocomplete.getPlaceFromIntent(it.data    
            latLng = place.latLng
            Log.d("place LatLng: ", latLng.toString())
             
            // move the camera position of the map

          // cameraPositionState.move(CameraUpdateFactory.newLatLngZoom(lonLat, 15f))
        }

    }
     FloatingActionButton(modifier = Modifier
            .align(Alignment.TopStart)
            .padding(10.dp),
            onClick = {
                launcher.launch(intent)
            }) {
            Icon(imageVector = Icons.Default.Search, contentDescription = 
      "")
        }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 WithThee