본문 바로가기
ios 뽀개기/ios앱

11 mapview

by 인생여희 2017. 11. 22.
반응형


mapview




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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//
//  ViewController.swift
//  MapView
//
//  Created by MacBookPro on 2017. 11. 22..
//  Copyright © 2017년 MacBookPro. All rights reserved.
//
 
import UIKit
import MapKit //맵관련
 
//지도 관련 클래스
class ViewController: UIViewController, CLLocationManagerDelegate {
 
    @IBOutlet weak var myMap: MKMapView! //mapView
    @IBOutlet weak var lbLocation1: UILabel!//라벨
    @IBOutlet weak var lbLocation2: UILabel!
    
    let locationManager = CLLocationManager() //지도 매니져 클래스
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        lbLocation1.text = ""   //아직 표시할 위치가 없어서 공백
        lbLocation2.text = ""
        locationManager.delegate = self //locationManager의 델리게이트를 self로 설정
        locationManager.desiredAccuracy = kCLLocationAccuracyBest //정확도를 최고로 설정
        locationManager.requestWhenInUseAuthorization() //위치데이터를 추적하기 위해서 사용자에게 승인 요구
        locationManager.startUpdatingLocation()     // 위치 업데이트 시작
        myMap.showsUserLocation = true              // 위치 보기 값을 true로 설정
        
        
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
 
    //위도와 경도, 영역 폭을 입력받아 지도에 표시
    func goLocation(latitud latitudeValue : CLLocationDegrees, longitude longitudeValue : CLLocationDegrees, delta span : Double) -> CLLocationCoordinate2D{
        
        //위도와 경도값을 매겨변수로 함수 호출
        let pLocation = CLLocationCoordinate2DMake(latitudeValue, longitudeValue)
        //범위 값을 매개변수로
        let spanValue = MKCoordinateSpanMake(span, span)
        let pResion = MKCoordinateRegionMake(pLocation, spanValue)
        myMap.setRegion(pResion, animated: true)
        
        return pLocation
    }
    
    //특정 위도와 경도에 핀설치하고 핀에 타이틀과 서브타이틀 문자열 표시하기(위도, 경도, 범위, 타이틀, 서브타이틀)
    func setAnnotation(latitude latitudeValue: CLLocationDegrees, longtitude longtitudeValue : CLLocationDegrees, delta span: Double, title strTitle : String, subtitle strSubtitle : String){
        
        let annotation = MKPointAnnotation()
        annotation.coordinate = goLocation(latitud : latitudeValue, longitude : longtitudeValue, delta : span)
        
        annotation.title = strTitle
        annotation.subtitle = strSubtitle
        myMap.addAnnotation(annotation)
    }
    
 
    //위치정보에서 국가, 지역, 도로를 추출하여 레이블에 표시
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations :[CLLocation]){
        
        let pLocation = locations.last //위치가 업데이트 되면 마지막 위치 값을 찾아낸다.
       
        //마지막 위치의 위도와 경도 값을 가지고 앞에서 만든 goLocation 함수를 호출 한다. delta값은 지도의 크기를 지정 한다.
        goLocation(latitud: (pLocation?.coordinate.latitude)!, longitude: (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 = country!
            
            //pm상수에서 지역 값이 존재하면 address 문자열에 추가한다.
            if pm!.locality != nil {
                address += " "
                address += pm!.locality!
            }
            
            //pm상수에서 도로값이 존재하면 address문자열에 추가한다.
            if pm!.thoroughfare != nil{
                address += " "
                address += pm!.thoroughfare!
            }
            
            self.lbLocation1.text = "현재위치"
            self.lbLocation2.text = address
        })
        
        //위치가 업데이트 되는것을 멈추게 한다.
        locationManager.stopUpdatingLocation()
    }
    
 
    //세그먼트 버튼 눌렀을 때
    @IBAction func sgChange(_ sender: UISegmentedControl) {
    
        if sender.selectedSegmentIndex == 0 {
            self.lbLocation1.text = ""
            self.lbLocation2.text = ""
            locationManager.startUpdatingLocation()
            
            
        }else if sender.selectedSegmentIndex == 1 {
          
            setAnnotation(latitude: 37.5593582, longtitude: 126.95928759999993, delta: 1, title: "보고계신위치", subtitle: "울집")
            self.lbLocation1.text = "보고계신위치"
            self.lbLocation2.text = "우리집"
            
        }else if sender.selectedSegmentIndex == 2 {
            
            setAnnotation(latitude: 37.5712897, longtitude: 126.98621430000003, delta: 0.1, title: "보고계신위치", subtitle: "회사")
            self.lbLocation1.text = "보고계신위치"
            self.lbLocation2.text = "회사"
        }
        
    }
}
 
 
cs


주의: 지도가 안나올경우


반응형

'ios 뽀개기 > ios앱' 카테고리의 다른 글

13 ios 스위프트 tapview  (0) 2017.11.23
12 ios 스위프트 pageControl  (0) 2017.11.23
10 웹뷰 webview  (0) 2017.11.22
9 alert 경고창 띄우기  (0) 2017.11.22
8 picker view 응용  (0) 2017.11.21

댓글