为了显示当前位置,我们不需要任何位置管理器GoogleMaps
。我们需要做的就是添加其中一个键或两个键.plist。所以请确保钥匙在那里。我用过NSLocationWhenInUseUsageDescription
key.
<key>NSLocationWhenInUseUsageDescription</key>
<string>Allow location</string>
另请确保您已致电GMSServices
provideAPIKey
方法并替换为API_KEY你在谷歌开发者控制台中生成的。此外,还应根据要求启用所有相关的 Google API。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
GMSServices.provideAPIKey("YOUR_API_KEY")
return true
}
所以,我假设您已经在谷歌开发者控制台中完成了所有设置和操作。
只需在控制器中写入以下行即可GoogleMap
可以显示位置允许/禁止提示并获取用户的许可。
mapView.isMyLocationEnabled = true
但是,这不会将您的地图动画显示到您当前的位置。但您可以手动拖动地图来查看当前位置,您会在当前位置看到一个蓝点。
但现在我们还希望在加载时动画到当前位置ViewController
。现在需要CLLocationManager
到达。所以说在其didUpdateLocation
委托,我们可以获取当前位置,并且可以将图形动画到当前位置。
这是我的完整控制器。
import UIKit
import GoogleMaps
class ViewController: UIViewController,GMSMapViewDelegate,CLLocationManagerDelegate {
@IBOutlet weak var mapView: GMSMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
mapView.isMyLocationEnabled = true
mapView.delegate = self
//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.camera(withLatitude: (location?.coordinate.latitude)!, longitude:(location?.coordinate.longitude)!, zoom:14)
mapView.animate(to: camera)
//Finally stop updating location otherwise it will come again and again in this delegate
self.locationManager.stopUpdatingLocation()
}
}
另一种方法是不使用didUpdateLocation
不使用位置管理器只是使用GMSMapViewDelegate
委托方法mapViewDidFinishTileRendering
func mapViewDidFinishTileRendering(_ mapView: GMSMapView) {
let location = mapView.myLocation
let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude:(location?.coordinate.longitude)!, zoom:14)
mapView.animate(to: camera)
}
每次地图渲染完成时都会调用它。
但这有一个限制,每当您拖动/捏合/缩放地图时,它总是会将您带到当前位置,因为每次玩地图时渲染完成。所以,你可以实施某种bool
这里的变量逻辑。
您可以使用以下方式获取您的位置
let yourCurrentLocation = mapView.myLocation
确保在设备而不是模拟器上执行此操作。如果您使用模拟器,则必须选择一些自定义位置,然后只有您才能看到蓝点。
我已经给出了这种类型的答案。检查这个Link https://stackoverflow.com/questions/38626649/how-to-show-my-current-location-on-google-maps-when-i-open-the-viewcontroller/38627279#38627279。但那是在 Swift 2.x 中。我在此答案中发布的内容是 Swift 3.x