HowTo—— Swift2.0在视图中显示地图
HowTo—— Swift2.0在视图中显示地图
4 人赞同了该文章
HowTo系列只提供代码和简单的说明,Xcode Version 12.0 beta 2 (12A6163b)
Swift2.0中,苹果添加了Map,让开发者可以非常容易的在View中添加需要的地图元素。
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
}
}
发布于 2020-07-09 16:48
漫思
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
2022-11-14 Web前端最新优化指标:FP、FCP、LCP、CLS、TTI、FID、TBT、FMP等
2022-11-14 前后端同构和模板渲染的区别是什么呢?
2022-11-14 关于进一步优化新冠肺炎疫情防控措施 科学精准做好防控工作的通知
2022-11-14 冬天能喝绿豆汤吗
2022-11-14 C# iText 7 切分PDF,处理PDF页面大小,添加水印
2022-11-14 C# 图片沿中心点进行角度旋转
2022-11-14 sql server 聚集索引,非聚集索引,Identity ,gudi,主键的概念和比较