![](/img/trans.png)
[英]Getting user's current location coordinates: MKMapItem vs CLLocationManager
[英]Get User's Current Location / Coordinates
如何存储用户的当前位置并在 map 上显示位置?
我能够在 map 上显示预定义的坐标,我只是不知道如何从设备接收信息。
我也知道我必须将一些项目添加到 Plist 中。 我怎样才能做到这一点?
要获取用户的当前位置,您需要声明:
let locationManager = CLLocationManager()
在viewDidLoad()
您必须实例化CLLocationManager
类,如下所示:
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
然后在 CLLocationManagerDelegate 方法中,您可以获得用户的当前位置坐标:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
在 info.plist 中,您必须添加NSLocationAlwaysUsageDescription
和您的自定义警报消息,例如; AppName(Demo App) 想使用您当前的位置。
你应该做这些步骤:
CoreLocation.framework
添加到 BuildPhases -> Link Binary With Libraries(从 XCode 7.2.1 开始不再需要)CoreLocation
导入您的类 - 很可能是 ViewController.swiftCLLocationManagerDelegate
添加到您的类声明中NSLocationWhenInUseUsageDescription
和NSLocationAlwaysUsageDescription
添加到 plist初始化位置管理器:
locationManager = CLLocationManager() locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation()
通过以下方式获取用户位置:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let locValue:CLLocationCoordinate2D = manager.location!.coordinate print("locations = \\(locValue.latitude) \\(locValue.longitude)") }
使用Swift 5更新iOS 12.2
您必须在 plist 文件中添加以下隐私权限
<key>NSLocationWhenInUseUsageDescription</key>
<string>Description</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Description</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Description</string>
这就是我的样子
获取当前位置并在 Swift 2.0 中的地图上显示
确保您已将CoreLocation和MapKit框架添加到您的项目中(XCode 7.2.1 不需要)
import Foundation
import CoreLocation
import MapKit
class DiscoverViewController : UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager!
override func viewDidLoad()
{
super.viewDidLoad()
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last! as CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
}
这是结果屏幕
导入库如:
import CoreLocation
设置委托:
CLLocationManagerDelegate
取变量,如:
var locationManager:CLLocationManager!
在 viewDidLoad() 上写下这段漂亮的代码:
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
编写 CLLocation 委托方法:
//MARK: - location delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation :CLLocation = locations[0] as CLLocation
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
self.labelLat.text = "\(userLocation.coordinate.latitude)"
self.labelLongi.text = "\(userLocation.coordinate.longitude)"
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
if (error != nil){
print("error in reverseGeocode")
}
let placemark = placemarks! as [CLPlacemark]
if placemark.count>0{
let placemark = placemarks![0]
print(placemark.locality!)
print(placemark.administrativeArea!)
print(placemark.country!)
self.labelAdd.text = "\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)"
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error \(error)")
}
现在设置访问该位置的权限,因此将这些键值添加到您的info.plist文件中
<key>NSLocationAlwaysUsageDescription</key>
<string>Will you allow this app to always know your location?</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
100% 工作没有任何问题。 已测试
NSLocationWhenInUseUsageDescription = 当应用程序在后台时请求使用位置服务的权限。 在你的 plist 文件中。
如果这有效,那么请投票给答案。
首先导入 Corelocation 和 MapKit 库:
import MapKit
import CoreLocation
从 CLLocationManagerDelegate 继承到我们的类
class ViewController: UIViewController, CLLocationManagerDelegate
创建一个 locationManager 变量,这将是您的位置数据
var locationManager = CLLocationManager()
创建一个函数来获取位置信息,具体来说这个确切的语法有效:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
在您的函数中为用户当前位置创建一个常量
let userLocation:CLLocation = locations[0] as CLLocation // note that locations is same as the one in the function declaration
停止更新位置,这可以防止您的设备在移动时不断更改窗口以将您的位置居中(如果您希望它以其他方式运行,则可以省略此项)
manager.stopUpdatingLocation()
从您刚刚定义的 userLocatin 获取用户坐标:
let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)
定义您希望地图的缩放程度:
let span = MKCoordinateSpanMake(0.2,0.2)
将这两者结合起来得到区域:
let region = MKCoordinateRegion(center: coordinations, span: span)//this basically tells your map where to look and where from what distance
现在设置区域并选择是否要它带动画去那里
mapView.setRegion(region, animated: true)
关闭你的功能}
从您的按钮或您想将 locationManagerDeleget 设置为 self 的其他方式
现在允许显示位置
指定准确度
locationManager.desiredAccuracy = kCLLocationAccuracyBest
授权:
locationManager.requestWhenInUseAuthorization()
为了能够授权定位服务,您需要将这两行添加到您的 plist
获取位置:
locationManager.startUpdatingLocation()
显示给用户:
mapView.showsUserLocation = true
这是我的完整代码:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func locateMe(sender: UIBarButtonItem) {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
manager.stopUpdatingLocation()
let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.2,0.2)
let region = MKCoordinateRegion(center: coordinations, span: span)
mapView.setRegion(region, animated: true)
}
}
斯威夫特 3.0
如果您不想在地图中显示用户位置,而只想将其存储在 firebase 或其他地方,请按照以下步骤操作,
import MapKit
import CoreLocation
现在在您的 VC 上使用 CLLocationManagerDelegate,您必须覆盖下面显示的最后三个方法。 您可以看到 requestLocation() 方法如何使用这些方法为您获取当前用户位置。
class MyVc: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
isAuthorizedtoGetUserLocation()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
}
}
//if we have no permission to access user location, then ask user for permission.
func isAuthorizedtoGetUserLocation() {
if CLLocationManager.authorizationStatus() != .authorizedWhenInUse {
locationManager.requestWhenInUseAuthorization()
}
}
//this method will be called each time when a user change his location access preference.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
print("User allowed us to access location")
//do whatever init activities here.
}
}
//this method is called by the framework on locationManager.requestLocation();
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did location updates is called")
//store the user location here to firebase or somewhere
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Did location updates is called but failed getting location \(error)")
}
}
现在,一旦用户登录到您的应用程序,您就可以对以下调用进行编码。 当 requestLocation() 被调用时,它将进一步调用上面的 didUpdateLocations,您可以将位置存储到 Firebase 或其他任何地方。
if CLLocationManager.locationServicesEnabled() {
locationManager.requestLocation();
}
如果您使用的是 GeoFire,那么在上面的 didUpdateLocations 方法中,您可以将位置存储如下
geoFire?.setLocation(locations.first, forKey: uid) where uid is the user id who logged in to the app. I think you will know how to get UID based on your app sign in implementation.
最后但并非最不重要的一点是,转到您的 Info.plist 并启用“使用使用说明时的隐私 - 位置”。
当您使用模拟器进行测试时,它始终为您提供一个您在模拟器 -> 调试 -> 位置中配置的自定义位置。
首先在你的项目中添加两个框架
1:地图套件
2:核心定位(从 XCode 7.2.1 开始不再需要)
在你的班级中定义
var manager:CLLocationManager!
var myLocations: [CLLocation] = []
然后在 viewDidLoad 方法中编码这个
manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
//Setup our Map View
mapobj.showsUserLocation = true
不要忘记在 plist 文件中添加这两个值
1: NSLocationWhenInUseUsageDescription
2: NSLocationAlwaysUsageDescription
用法:
在类中定义字段
let getLocation = GetLocation()
通过简单的代码在类的函数中使用:
getLocation.run {
if let location = $0 {
print("location = \(location.coordinate.latitude) \(location.coordinate.longitude)")
} else {
print("Get Location failed \(getLocation.didFailWithError)")
}
}
班级:
import CoreLocation
public class GetLocation: NSObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
var locationCallback: ((CLLocation?) -> Void)!
var locationServicesEnabled = false
var didFailWithError: Error?
public func run(callback: @escaping (CLLocation?) -> Void) {
locationCallback = callback
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
manager.requestWhenInUseAuthorization()
locationServicesEnabled = CLLocationManager.locationServicesEnabled()
if locationServicesEnabled { manager.startUpdatingLocation() }
else { locationCallback(nil) }
}
public func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
locationCallback(locations.last!)
manager.stopUpdatingLocation()
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
didFailWithError = error
locationCallback(nil)
manager.stopUpdatingLocation()
}
deinit {
manager.stopUpdatingLocation()
}
}
不要忘记在 info.plist 中添加“NSLocationWhenInUseUsageDescription”。
import CoreLocation
import UIKit
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status != .authorizedWhenInUse {return}
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
let locValue: CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
}
由于对requestWhenInUseAuthorization
的调用是异步的,因此应用在用户授予权限或拒绝权限后调用locationManager
函数。 因此,在用户授予权限的情况下,将您的位置获取代码放置在该函数中是合适的。 这是我在上面找到的最好的教程。
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization();
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
else{
print("Location service disabled");
}
}
这是您的视图确实加载方法,并且在 ViewController 类中还包括 mapStart 更新方法,如下所示
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue : CLLocationCoordinate2D = manager.location.coordinate;
let span2 = MKCoordinateSpanMake(1, 1)
let long = locValue.longitude;
let lat = locValue.latitude;
print(long);
print(lat);
let loadlocation = CLLocationCoordinate2D(
latitude: lat, longitude: long
)
mapView.centerCoordinate = loadlocation;
locationManager.stopUpdatingLocation();
}
另外不要忘记在您的项目中添加 CoreLocation.FrameWork 和 MapKit.Framework (从XCode 7.2.1 开始不再需要)
import Foundation
import CoreLocation
enum Result<T> {
case success(T)
case failure(Error)
}
final class LocationService: NSObject {
private let manager: CLLocationManager
init(manager: CLLocationManager = .init()) {
self.manager = manager
super.init()
manager.delegate = self
}
var newLocation: ((Result<CLLocation>) -> Void)?
var didChangeStatus: ((Bool) -> Void)?
var status: CLAuthorizationStatus {
return CLLocationManager.authorizationStatus()
}
func requestLocationAuthorization() {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
manager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func getLocation() {
manager.requestLocation()
}
deinit {
manager.stopUpdatingLocation()
}
}
extension LocationService: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
newLocation?(.failure(error))
manager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.sorted(by: {$0.timestamp > $1.timestamp}).first {
newLocation?(.success(location))
}
manager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined, .restricted, .denied:
didChangeStatus?(false)
default:
didChangeStatus?(true)
}
}
}
需要在所需的 ViewController 中编写此代码。
//NOTE:: Add permission in info.plist::: NSLocationWhenInUseUsageDescription
let locationService = LocationService()
@IBAction func action_AllowButtonTapped(_ sender: Any) {
didTapAllow()
}
func didTapAllow() {
locationService.requestLocationAuthorization()
}
func getCurrentLocationCoordinates(){
locationService.newLocation = {result in
switch result {
case .success(let location):
print(location.coordinate.latitude, location.coordinate.longitude)
case .failure(let error):
assertionFailure("Error getting the users location \(error)")
}
}
}
func getCurrentLocationCoordinates() {
locationService.newLocation = { result in
switch result {
case .success(let location):
print(location.coordinate.latitude, location.coordinate.longitude)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
return
}
if (placemarks?.count)! > 0 {
print("placemarks", placemarks!)
let pmark = placemarks?[0]
self.displayLocationInfo(pmark)
} else {
print("Problem with the data received from geocoder")
}
})
case .failure(let error):
assertionFailure("Error getting the users location \(error)")
}
}
}
这是一个对我有用的复制粘贴示例。
http://swiftdeveloperblog.com/code-examples/determine-users-current-location-example-in-swift/
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
determineMyCurrentLocation()
}
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
// Call stopUpdatingLocation() to stop listening for location updates,
// other wise this function will be called every time when user location changes.
// manager.stopUpdatingLocation()
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
}
以前的所有答案都没有真正正确地遵循正确的步骤集。 设置CLLocationManager
时,您最初不需要调用CLLocationManager.locationServicesEnabled()
或locationManager.requestWhenInUseAuthorization()
。 在您确认您拥有授权之前,您不应该调用startUpdatingLocation()
。
要开始,请添加所需的隐私设置(如果尚未完成)。 Select 您的应用程序目标和 go 到“信息”选项卡。 在“自定义 iOS 目标属性”部分下,右键单击 select“添加行”。 向下滚动到“隐私”条目和 select:
根据您的应用程序的需要。 对于该值,请务必输入一个句子,向用户解释为什么您的应用需要访问他们的位置。 如果给定的描述对用户没有用,您的应用可能会被 Apple 拒绝。
然后使用以下(大量注释)代码作为获取用户在视图 controller 中的位置的示例:
import UIKit
import CoreLocation
class ViewController: UIViewController {
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Setup the location manager
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation // Or other desired accuracy
// That's it for the initial setup. Everything else is handled in the
// locationManagerDidChangeAuthorization delegate method.
}
}
extension ViewController: CLLocationManagerDelegate {
// This is called as soon as the location manager is setup (in viewDidLoad)
// This is called when the user responds to the privacy dialog
// This is called if the user changes the privacy setting in the Settings app
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
switch manager.authorizationStatus {
case .notDetermined:
// Request the appropriate authorization based on the needs of the app
manager.requestWhenInUseAuthorization()
// manager.requestAlwaysAuthorization()
case .restricted:
print("Sorry, restricted")
// Optional: Offer to take user to app's settings screen
case .denied:
print("Sorry, denied")
// Optional: Offer to take user to app's settings screen
case .authorizedAlways, .authorizedWhenInUse:
// The app has permission so start getting location updates
manager.startUpdatingLocation()
@unknown default:
print("Unknown status")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Received \(locations.count) locations")
// Some location updates can be invalid or have insufficient accuracy.
// Find the first location that has sufficient horizontal accuracy.
// If the manager's desiredAccuracy is one of kCLLocationAccuracyNearestTenMeters,
// kCLLocationAccuracyHundredMeters, kCLLocationAccuracyKilometer, or kCLLocationAccuracyThreeKilometers
// then you can use $0.horizontalAccuracy <= manager.desiredAccuracy. Otherwise enter the number of meters desired.
if let location = locations.first(where: { $0.horizontalAccuracy <= 40 }) {
print("Good location found: \(location)")
// Call the following if you don't need any more updates
manager.stopUpdatingLocation()
// Do something useful with the found location
// - show on a map
// - Reverse geocode to get the address
// - send to server
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location manager error: \(error)")
}
}
// its with strongboard
@IBOutlet weak var mapView: MKMapView!
//12.9767415,77.6903967 - exact location latitude n longitude location
let cooridinate = CLLocationCoordinate2D(latitude: 12.9767415 , longitude: 77.6903967)
let spanDegree = MKCoordinateSpan(latitudeDelta: 0.2,longitudeDelta: 0.2)
let region = MKCoordinateRegion(center: cooridinate , span: spanDegree)
mapView.setRegion(region, animated: true)
100% 在 iOS Swift 4 中工作,作者:Parmar Sajjad
第 1 步:转到 GoogleDeveloper Api 控制台并创建您的 ApiKey
第 2 步:转到项目安装 Cocoapods GoogleMaps pod
第 3 步:转到 AppDelegate.swift 导入 GoogleMaps 和
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
GMSServices.provideAPIKey("ApiKey")
return true
}
第 4 步:导入 UIKit 导入 GoogleMaps 类 ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapview: UIView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManagerSetting()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManagerSetting() {
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.showCurrentLocationonMap()
self.locationManager.stopUpdatingLocation()
}
func showCurrentLocationonMap() {
let
cameraposition = GMSCameraPosition.camera(withLatitude: (self.locationManager.location?.coordinate.latitude)! , longitude: (self.locationManager.location?.coordinate.longitude)!, zoom: 18)
let mapviewposition = GMSMapView.map(withFrame: CGRect(x: 0, y: 0, width: self.mapview.frame.size.width, height: self.mapview.frame.size.height), camera: cameraposition)
mapviewposition.settings.myLocationButton = true
mapviewposition.isMyLocationEnabled = true
let marker = GMSMarker()
marker.position = cameraposition.target
marker.snippet = "Macczeb Technologies"
marker.appearAnimation = GMSMarkerAnimation.pop
marker.map = mapviewposition
self.mapview.addSubview(mapviewposition)
}
}
第 5 步:打开 info.plist 文件并在下面添加 Privacy - Location When In Use Usage Description ......在主故事板文件基本名称下方
第 6 步:运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.