간단한 안드로이드 앱 만들기 (날씨 앱)
16. SearchActivity '현 위치' item 추가, MainActivity 카메라 갱신
리저브콜드브루
2025. 2. 27. 11:31
728x90
반응형
- SearchActivity에 현 위치 정보에 대한 아이템을 추가
- MainActivity가 재사용될 때 맵 카메라도 위치정보에 맞게 갱신
SearchActivity
- addCurLoccationKey(): 현 위치(키값) 정보를 리스트에 추가
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)
...
cityList = CityDataProvider.cityList
addCurLocationKey()
...
}
private fun addCurLocationKey()
{
this.lifecycleScope.launch {
val locationKey = locationDataStore.locationKey.first()
if (locationKey != null) {
// 기존 cityList의 맨 앞에 새로운 값을 추가한 새 리스트 생성
val updatedCityList = listOf(
CityCallInfo(
"현 위치",
locationKey.split("_")[0].toDouble(),
locationKey.split("_")[1].toDouble()
)
) + cityList
// 새로운 리스트를 기존 리스트로 대체
cityList = updatedCityList
}
}
}
실행 화면
MapController
- updateCurPosition() 삭제
- setCurrentLatLng() 추가
fun setCurrentLatLng(latitude: Double, longitude: Double) {
currentLatLng = LatLng.from(latitude, longitude)
}
MainActivity
- 필요한 곳에 setCurrentLatLng()추가
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
intent?.let {
val cityName = it.getStringExtra("CITY_NAME")
val latitude = it.getDoubleExtra("CITY_LATITUDE", 0.0)
val longitude = it.getDoubleExtra("CITY_LONGITUDE", 0.0)
mapController.setCurrentLatLng(latitude, longitude)
...
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun updateLocationUI() {
lifecycleScope.launch {
val latitude = locationDataStore.cur_latitude.first()
val longitude = locationDataStore.cur_longitude.first()
if (latitude != null && longitude != null) {
Log.d("MainActivity", "위도: $latitude, 경도: $longitude")
mapController.setCurrentLatLng(latitude, longitude)
val geocoder = Geocoder(this@MainActivity, Locale.getDefault())
geocoder.getFromLocation(latitude, longitude, 1) { addresses ->
...
}
} else {
textViewLocation.text = "위치 정보 없음"
}
}
}
실행 모습
728x90
반응형