我正在使用iOS(Swift)的Google Maps SDK。
有谁知道如何“当我打开ViewController时在Google地图上显示我的当前位置”?
实际上,它就像Google Maps App。当您打开Google地图时,蓝点将显示您的当前位置。您不需要第一次按下“ myLocationButton”。
所以这是代码:
import UIKit
import CoreLocation
import GoogleMaps
class GoogleMapsViewer: UIViewController {
@IBOutlet weak var mapView: GMSMapView!
let locationManager = CLLocationManager()
let didFindMyLocation = false
override func viewDidLoad() {
super.viewDidLoad()
let camera = GMSCameraPosition.cameraWithLatitude(23.931735,longitude: 121.082711, zoom: 7)
let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
mapView.myLocationEnabled = true
self.view = mapView
// GOOGLE MAPS SDK: BORDER
let mapInsets = UIEdgeInsets(top: 80.0, left: 0.0, bottom: 45.0, right: 0.0)
mapView.padding = mapInsets
locationManager.distanceFilter = 100
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
// GOOGLE MAPS SDK: COMPASS
mapView.settings.compassButton = true
// GOOGLE MAPS SDK: USER'S LOCATION
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
}
}
// MARK: - CLLocationManagerDelegate
extension GoogleMapsViewer: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
locationManager.startUpdatingLocation()
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 20, bearing: 0, viewingAngle: 0)
locationManager.stopUpdatingLocation()
}
}
}
有人帮忙吗?太感谢了!
对于Swift 3.x解决方案,请检查此答案
首先,所有人必须在Info.plist文件中输入一个密钥 NSLocationWhenInUseUsageDescription
添加此键后,只需创建一个CLLocationManager
变量,然后执行以下操作
@IBOutlet weak var mapView: GMSMapView!
var locationManager = CLLocationManager()
class YourControllerClass: UIViewController,CLLocationManagerDelegate {
//Your map initiation code
let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
self.view = mapView
self.mapView?.myLocationEnabled = true
//Location Manager code to fetch current location
self.locationManager.delegate = self
self.locationManager.startUpdatingLocation()
}
//Location Manager delegates
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let camera = GMSCameraPosition.cameraWithLatitude((location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 17.0)
self.mapView?.animateToCameraPosition(camera)
//Finally stop updating location otherwise it will come again and again in this delegate
self.locationManager.stopUpdatingLocation()
}
运行代码时,将弹出“允许”和“不允许位置”信息。只需单击允许,您将看到您的当前位置。
确保在设备而不是模拟器上执行此操作。如果使用模拟器,则必须选择一些自定义位置,然后只有您才能看到蓝点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句