kakaoMap SDK를 사용해서 카카오지도를 띄우고, 검색을 이용해서 해당지역을 검색하면 LabelStyles를 이용해서 해당 위치에 라벨을 표시하는 작업을 하고있었다
그러다가 해당 맵이있는 프레그먼트를 벗어난다음 다시 Map이 있는 화면으로 돌아가면 앱이 꺼지는 오류가 발생했다
로그캣의 오류를 살펴봤더니 아래와같은 오류가 발생했다
LabelStyles를 사용해서 라벨을 생성하고 표시할때, LabelStyles가 null을 반환할 경우 getTextStyleCount() 메서드를 호출하려고 할 때 발생하는 오류인것같았다
java.lang.NullPointerException: Attempt to invoke virtual method 'int com.kakao.vectormap.label.LabelStyles.getTextStyleCount()' on a null object reference
로그캣 오류
따라서 if문을 사용해서 LabelStyles가 null인지 확인하고, null이 아닐때만 라벨을 생성하고 추가하도록 처리해서 오류를 해결했다
// 해당위치로 이동, 라벨 표시
private fun setMapData(searchDocumentsResponse: SearchDocumentsResponse) {
// 좌표값 포맷팅
// y=37.4560044656444, x=126.705258070068 -> 여기서 소숫점 6자리숫자까지만 표시!
val latitude = searchDocumentsResponse.y
val longitude = searchDocumentsResponse.x
val latitude_formatter = String.format("%.6f", latitude).toDouble() // %.6f는 소수점 이하 6자리까지만 표시
val longitude_formatter = String.format("%.6f", longitude).toDouble()
// 이동할 위치(위도,경도) 설정
val camera = CameraUpdateFactory.newCenterPosition(LatLng.from(latitude_formatter, longitude_formatter))
// 해당위치로 지도 이동
// kakaoMap?.moveCamera(camera)
kakaoMap?.moveCamera(camera, CameraAnimation.from(500,true,true)) // 애니메이션 적용해서 이동
// 커스텀으로 라벨 생성 및 가져옴
// 1. LabelStyles 생성 - Icon 이미지 하나만 있는 스타일
val styles = kakaoMap?.labelManager?.addLabelStyles(LabelStyles.from(LabelStyle.from(R.drawable.ic_map_red)))
// 2. LabelOptions 생성
val options = LabelOptions.from(LatLng.from(latitude_formatter, longitude_formatter)).setStyles(styles)
// 3. LabelLayer 가져옴 (또는 커스텀 Layer 생성)
val layer = kakaoMap?.labelManager?.getLayer()
// 4.options 을 넣어 Label 생성
layer?.addLabel(options)
}
기존코드
// 해당위치로 이동, 라벨 표시
private fun setMapData(searchDocumentsResponse: SearchDocumentsResponse) {
// 좌표값 포맷팅
// y=37.4560044656444, x=126.705258070068 -> 여기서 소숫점 6자리숫자까지만 표시!
val latitude = searchDocumentsResponse.y
val longitude = searchDocumentsResponse.x
val latitude_formatter = String.format("%.6f", latitude).toDouble() // %.6f는 소수점 이하 6자리까지만 표시
val longitude_formatter = String.format("%.6f", longitude).toDouble()
// 이동할 위치(위도,경도) 설정
val camera = CameraUpdateFactory.newCenterPosition(LatLng.from(latitude_formatter, longitude_formatter))
// 해당위치로 지도 이동
// kakaoMap?.moveCamera(camera)
kakaoMap?.moveCamera(camera, CameraAnimation.from(500,true,true)) // 애니메이션 적용해서 이동
// 커스텀으로 라벨 생성 및 가져옴
// 1. LabelStyles 생성 - Icon 이미지 하나만 있는 스타일
val styles = kakaoMap?.labelManager?.addLabelStyles(LabelStyles.from(LabelStyle.from(R.drawable.ic_map_red)))
// styles가 null이 아닐때만, LabelOptions 생성하고 라벨추가
if(styles != null){
// 2. LabelOptions 생성
val options = LabelOptions.from(LatLng.from(latitude_formatter, longitude_formatter)).setStyles(styles)
// 3. LabelLayer 가져옴 (또는 커스텀 Layer 생성)
val layer = kakaoMap?.labelManager?.getLayer()
// 4.options 을 넣어 Label 생성
layer?.addLabel(options)
}else{
Log.e("kakaoMap", "LabelStyles null값 에러")
}
}
if문을 사용해서 수정한 코드