在地图SwiftUI上显示用户位置 [英] Show user location on map SwiftUI
本文介绍了在地图SwiftUI上显示用户位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试加载地图,并在用户的位置上显示初始位置,并使用SwiftUI在地图上显示用户的位置.我不知道如何在SwiftUI中做到这一点.
I am trying to load a map and have the initial location on user's location as well as showing the user's location on the map using SwiftUI. I don't know how to do that in SwiftUI.
我试图将'view.showsUserLocation = true'放在updateUIView函数中,但是它不起作用.
I have tried to put 'view.showsUserLocation = true' in updateUIView function but it is not working.
import SwiftUI
import MapKit
struct MapView : UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
MKMapView(frame: .zero)
}
func updateUIView(_ view: MKMapView, context: Context) {
view.showsUserLocation = true
let coordinate = CLLocationCoordinate2D(
latitude: 34.011286, longitude: -116.166868)
let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
let region = MKCoordinateRegion(center: view.userLocation.location?.coordinate ?? coordinate, span: span)
view.setRegion(region, animated: true)
}
}
当我尝试打印该位置时,该位置为零.
The location comes nil when I tried to print it.
推荐答案
在Info.plist
然后尝试更新以下功能:
Then try with updating below function:
func updateUIView(_ view: MKMapView, context: Context) {
view.showsUserLocation = true
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
// self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.locationManager.startUpdatingLocation()
//Temporary fix: App crashes as it may execute before getting users current location
//Try to run on device without DispatchQueue
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
let locValue:CLLocationCoordinate2D = self.locationManager.location!.coordinate
print("CURRENT LOCATION = \(locValue.latitude) \(locValue.longitude)")
let coordinate = CLLocationCoordinate2D(
latitude: locValue.latitude, longitude: locValue.longitude)
let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
let region = MKCoordinateRegion(center: coordinate, span: span)
view.setRegion(region, animated: true)
})
}
}
这篇关于在地图SwiftUI上显示用户位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文