티스토리 뷰

Xcode(버전11.2.1)를 이용하여 맵 뷰(Map View) 지도 앱을 만든다:)

 

 

 

- 스토리보드 앱 화면 구성

Segmented Control, Map Kit View, Label 을 추가한다.

Segmented Control의 Segments를 3으로 선택해 하나 추가한다.

 

 

 

- 아울렛 변수 추가

map view name 'myMap'

label name 'lblLocationInfo1'

label name 'lblLocationInfo2'

 

맵 뷰 아울렛 변수 추가시 오류가 발생한다.

설정창에서 유형(type)을 MKMapView로 설정했는데, 이를 받쳐줄 MapKit가 아직 없기 때문.

MapKit는 지도를 확대, 축소 및 이동하는 등 지도에 관한 여러 기능을 제공한다.

사용자의 터치를 인식하여 기능을 수행하기 위해선 이 작업이 필요하다.

import MapKit 코드를 추가한다.

 

 

 

- 액션 함수 추가

sgmented control name 'sgChangeLocation'

 

 

 

경우에 따라 지도가 나타나지 않을 수 있다. 

이런 경우 경고창을 확인한다.

This app has attempted to access privacy-sensitive data without a usage description.

위와 같은 메세지가 있다면, Info.plist을 수정한다. (사진참고)

Info.plist -> Information Property List + 버튼 (리스트 새로 추가) ->

Privacy - Location When In Use Usage Description -> Value : App needs location servers for stuff. 

 

 

 

앱이 사용자 위치에 접근하도록 허용할 것인지 물어보는 얼럿창이 띄워진다.

Allow while Using App을 눌러 앱을 사용하는 동안 위치 접근을 허용했다.

 

 

 

- ios 시뮬레이터의 언어와 지역 변경

시뮬레이터 setting -> General -> Language & Region 이동

iPhone Language -> 한국어, Region -> 대한민국 으로 변경한다.

다시 홈으로 이동하면 한글로 변경된 것을 확인할 수 있다.

 

 

 

시뮬레이터는 GPS 지원이 되지 않아서 현재 위치를 지정했다.

시뮬레이터 메뉴 Debug -> Location -> Custom Location...을 선택하여 위치를 수정한다.

내가 설정한 위치는 탐앤탐스커피 금천본점이다. 

서울 금천구 시흥대로 398 (독산동 1012-5)

 

 

 

전체 소스 보기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//
//  ViewController.swift
//  day191204_Map
//
//  Created by 무니 on 04/12/2019.
//  Copyright © 2019 com.mooni. All rights reserved.
//
 
import UIKit
import MapKit
 
class ViewController: UIViewController, CLLocationManagerDelegate {
    @IBOutlet var myMap: MKMapView!
    @IBOutlet var lblLocationInfo1: UILabel!
    @IBOutlet var lblLocationInfo2: UILabel!
    
    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        lblLocationInfo1.text = ""
        lblLocationInfo2.text = ""
        locationManager.delegate = self
        // 정확도를 최고로 설정
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        // 위치 데이터를 추적하기 위해 사용자에게 승인 요구
        locationManager.requestWhenInUseAuthorization()
        // 위치 업데이트를 시작
        locationManager.startUpdatingLocation()
        // 위치 보기 설정
        myMap.showsUserLocation = true
    }
    
    // 위도와 경도, 스팬(영역 폭)을 입력받아 지도에 표시
    func goLocation(latitudeValue: CLLocationDegrees,
                    longtudeValue: CLLocationDegrees,
                    delta span: Double) -> CLLocationCoordinate2D {
        let pLocation = CLLocationCoordinate2DMake(latitudeValue, longtudeValue)
        let spanValue = MKCoordinateSpan(latitudeDelta: span, longitudeDelta: span)
        let pRegion = MKCoordinateRegion(center: pLocation, span: spanValue)
        myMap.setRegion(pRegion, animated: true)
        return pLocation
    }
    
    // 특정 위도와 경도에 핀 설치하고 핀에 타이틀과 서브 타이틀의 문자열 표시
    func setAnnotation(latitudeValue: CLLocationDegrees,
                       longitudeValue: CLLocationDegrees,
                       delta span :Double,
                       title strTitle: String,
                       subtitle strSubTitle:String){
        let annotation = MKPointAnnotation()
        annotation.coordinate = goLocation(latitudeValue: latitudeValue, longtudeValue: longitudeValue, delta: span)
        annotation.title = strTitle
        annotation.subtitle = strSubTitle
        myMap.addAnnotation(annotation)
    }
    
    // 위치 정보에서 국가, 지역, 도로를 추출하여 레이블에 표시
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let pLocation = locations.last
        _ = goLocation(latitudeValue: (pLocation?.coordinate.latitude)!,
                   longtudeValue: (pLocation?.coordinate.longitude)!,
                   delta: 0.01)
        CLGeocoder().reverseGeocodeLocation(pLocation!, completionHandler: {(placemarks, error) -> Void in
            let pm = placemarks!.first
            let country = pm!.country
            var address: String = ""
            if country != nil {
                address = country!
            }
            if pm!.locality != nil {
                address += " "
                address += pm!.locality!
            }
            if pm!.thoroughfare != nil {
                address += " "
                address += pm!.thoroughfare!
            }
            self.lblLocationInfo1.text = "현재 위치"
            self.lblLocationInfo2.text = address
        })
        locationManager.stopUpdatingLocation()
    }
    
    // 세크먼트 컨트롤을 선택하였을 때 호출
    @IBAction func sgChangeLocation(_ sender: UISegmentedControl) {
        if sender.selectedSegmentIndex == 0 {
            // "현재 위치" 선택 - 현재 위치 표시
            self.lblLocationInfo1.text = ""
            self.lblLocationInfo2.text = ""
            locationManager.startUpdatingLocation()
        } else if sender.selectedSegmentIndex == 1 {
            // "물왕저수지 정통밥집" 선택 - 핀을 설치하고 위치 정보 표시
            setAnnotation(latitudeValue: 37.3826616, longitudeValue: 126.840719, delta: 0.1, title: "물왕저수지 정통밥집", subtitle: "경기 시흥시 동서로857번길 6")
            self.lblLocationInfo1.text = "보고 계신 위치"
            self.lblLocationInfo2.text = "물왕저수지 정통밥집"
        } else if sender.selectedSegmentIndex == 2 {
            // "이디야 북한산점" 선택 - 핀을 설치하고 위치 정보 표시
            setAnnotation(latitudeValue: 37.6447360, longitudeValue: 127.005575, delta: 0.1, title: "이디야 북한산점", subtitle: "서울 강북구 4.19로 85")
                       self.lblLocationInfo1.text = "보고 계신 위치"
                       self.lblLocationInfo2.text = "이디야 북한산점"
        }
            
    }
    
}
 
 
cs

 

 

 

시뮬레이터 결과 보기

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함