gpt4 book ai didi

ios - 使 map 缩放到用户位置和注释(swift 2)

转载 作者:IT王子 更新时间:2023-10-29 05:42:39 24 4
gpt4 key购买 nike

我正在使用 mapkit。我希望 map 缩放以显示用户的位置和注释点,而不是仅仅缩放到用户的当前位置。

目前我有:

                            let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake(mapLat, mapLon)
annotation.title = mapTitle
self.map.addAnnotation(annotation)

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLoction: CLLocation = locations[0]
let latitude = userLoction.coordinate.latitude
let longitude = userLoction.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
self.map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}

它只是缩放到用户的位置并锁定在该位置。当我尝试滚动时,它只是跳回到用户的位置。我究竟做错了什么?如何允许用户在不跳回当前位置的情况下在 map 上缩放或移动?

我正在尝试放大以在同一 View 中显示注释和用户位置。即使注释距离很远,我也希望它缩放以同时显示用户和注释。

最佳答案

它直接跳回到用户的位置,因为 didUpdateLocations 方法被调用了很多次。有两种解决方案。

1) 使用requestLocation

如果您使用requestLocation 方法而不是startUpdatingLocationdidUpdateLocations 方法只会被调用一次

if #available(iOS 9.0, *) {
locationManager.requestLocation()
} else {
// Fallback on earlier versions
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLoction: CLLocation = locations[0]
let latitude = userLoction.coordinate.latitude
let longitude = userLoction.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
self.map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}

2)使用标志

var isInitialized = false

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if !isInitialized {
// Here is called only once
isInitialized = true

let userLoction: CLLocation = locations[0]
let latitude = userLoction.coordinate.latitude
let longitude = userLoction.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
self.map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}
}

关于ios - 使 map 缩放到用户位置和注释(swift 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33044148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com