HowTo—— Swift2.0 在视图中显示地图

鼓励作者

Swift2.0 中,苹果添加了 Map,让开发者可以非常容易的在 View 中添加需要的地图元素。

健康笔记 - 新生活从记录开始
50% OFF for WWDC23

健康笔记是一款智能的数据管理和分析工具,让您完全掌控自己和全家人的健康信息。作为慢性病患者,肘子深知健康管理的重要与难度。创建健康笔记的初心,就是要为您提供一款轻松高效的健康信息记录与分析工具

推荐
import SwiftUI
import MapKit

struct MapView: View{
    //设置初始显示区域
    @State private var region:MKCoordinateRegion = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 38.92083, longitude: 121.63917),
        span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)
    )
    
    //设置是否持续跟踪用户当前位置
    @State private var trackmode = MapUserTrackingMode.follow
    
    //设置标记点信息
    let dots:[MapDot] = [
        MapDot(title:"point1",
               coordinate:CLLocationCoordinate2D(latitude: 38.92083, longitude: 121.63917),
               color:.red),
        MapDot(title:"point2",
               coordinate:CLLocationCoordinate2D(latitude: 38.92183, longitude: 121.62717),
               color:.blue)
    ]
    
    @StateObject var store = Store()
    
    var body: some View {
        ZStack(alignment:.bottom){
            Map(coordinateRegion: $region,
                interactionModes: .all, //.pan .zoom .all
                showsUserLocation: true, //是否显示用户当前位置
                userTrackingMode:$trackmode, //是否更新用户位置
                annotationItems:dots //标记点数据
            ){item in
                //标记点显示,也可以直接使用内置的 MapPin, 不过 MapPin 无法响应用户输入
                MapAnnotation(coordinate: item.coordinate  ){
                    //不知道是否是 bug, 目前 iOS 下无法显示 Text,maxOS 可以显示
                    Label(item.title, systemImage: "star.fill")
                        .font(.body)
                        .foregroundColor(item.color)
                        .onTapGesture {
                            print(item.title)
                        }
                }
            }
        }
        .edgesIgnoringSafeArea(.all)
    }
}

//标记点数据,要求符合 Identifiable
struct MapDot:Identifiable{
    let id = UUID()
    let title:String
    let coordinate:CLLocationCoordinate2D
    let color:Color
}

class Store:ObservableObject {
    let manager = CLLocationManager()
    init() {
        //请求位置访问权限。需要在 plist 中设置 Privacy - Location When In Use Usage Description
        //如果不需要显示当前用户位置,则无需申请权限
        #if os(iOS)
            manager.requestWhenInUseAuthorization()
        #endif
    }
}

希望本文能够对你有所帮助。同时也欢迎你通过 TwitterDiscord 频道或下方的留言板与我进行交流。

本博客文章采用CC 4.0 协议,转载需注明出处和作者。

鼓励作者