[iOS] Geocoding

RudinP·2024년 3월 28일
0

Study

목록 보기
211/226

Geocoding

  • 주소나 지명을 좌표로 바꾸는 작업
  • 반대로 좌표 -> 주소는 ReverseGeocoding 이다.
  • 기본 지오코딩을 그래서 ForwardGeocoding이라고 부르기도 한다.

  • 지오코딩을 지원해주는 객체로, 리버스와 포워드 전부 지원한다.
  • 애플 서버로 요청을 보낸 다음 응답을 받는 방식이다.
    • 따라서 주소 체계가 미국 방식이다.
    • 살짝 불편하지만 일반적인 경우라면 충분하다.
  • 애플 서버에 보내기 때문에 짧은 시간동안 너무 많은 요청을 보낸 경우 에러가 리턴된다.
    • 따라서 캐시를 적절하게 구현해야 한다.

Reverse Geocoding


func reverseGeocoding(location: CLLocation){
        let geocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(location, preferredLocale: Locale(identifier: "ko_kr")) { placemarks, error in
            if let first = placemarks?.first{
                self.addressLabel.text = first.name
            }
        }
    }
  • [CLPlacemark]?에는 보통 한 개의 주소가 저장되지만, 만약 한 좌표에 여러개의 주소가 존재하는 경우 여러 원소가 포함된 배열로 리턴된다.
  • prefferedLocale: 한국인 ko_kr를 입력해준다.
  • first.name: name 속성에는 보통 해당 좌표와 가까운 주변 지역 중에서 대표적인 지명이 저장되어있다. 하지만 항상 저장되어있는 것은 아니기때문에, 이 값에 의지하면 안된다.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let currentLocation = locations.last{
            latitudeLabel.text = "\(currentLocation.coordinate.latitude)"
            longtitudeLabel.text = "\(currentLocation.coordinate.longitude)"
            
            reverseGeocoding(location: currentLocation)
        }
    }
  • didUpdateLocations와 같은 사용할 곳에서 메소드를 사용하는 것을 잊지 말자 ^^

CLPlaceMark의 프로퍼티

//first는 CLPlaceMark의 first 원소를 저장한 객체
print("Country", first.country)
print("Postal Code", first.postalCode) // 나름 정확하게 나옴
print("Admin Area", first.administrativeArea, first.subAdministrativeArea)//시나 도 단위 저장. 서브에는 부가 정보가 저장되는데, 보통은 nil
print("Locality", first.locality, first.subLocality)//도시 레벨 정보 저장. locality: 시. subLocality: 동 저장
print("Street", first.thoroughfare, first.subThoroughfare)//보통은 큰 도로가 아니면 nil이므로 사용할 일 X. 도로명 아님!

  • 좌표에 따라서 설명과 다르게 저장되어 있는 경우도 있어, 매번 출력하여 값을 확인하는 것이 좋다.
profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글