斯威夫特 4
禁用默认的谷歌地图当前位置标记(默认禁用):
mapView.isMyLocationEnabled = false
创建一个标记作为视图控制器的实例属性(因为委托需要访问它):
let currentLocationMarker = GMSMarker()
GMSMarker 初始化器允许将 UIImage 或 UIView 作为自定义图形,不幸的是,UIImageView 不是。如果您想对图形进行更多控制,请使用UIView。在您的 loadView 或 viewDidLoad(无论您在哪里配置地图)中,配置标记并将其添加到地图中:
// configure custom view
let currentLocationMarkerView = UIView()
currentLocationMarkerView.frame.size = CGSize(width: 40, height: 40)
currentLocationMarkerView.layer.cornerRadius = 40 / 4
currentLocationMarkerView.clipsToBounds = true
let currentLocationMarkerImageView = UIImageView(frame: currentLocationMarkerView.bounds)
currentLocationMarkerImageView.contentMode = .scaleAspectFill
currentLocationMarkerImageView.image = UIImage(named: "masterAvatar")
currentLocationMarkerView.addSubview(currentLocationMarkerImageView)
// add custom view to marker
currentLocationMarker.iconView = currentLocationMarkerView
// add marker to map
currentLocationMarker.map = mapView
剩下的就是给标记一个坐标(最初和每次用户的位置改变时),你可以通过CLLocationManagerDelegate委托来完成。
extension MapViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let lastLocation = locations.last!
// update current location marker
currentLocationMarker.position = CLLocationCoordinate2D(latitude: lastLocation.coordinate.latitude, longitude: lastLocation.coordinate.longitude)
}
}
位置管理器生成的前几个位置可能不是很准确(尽管有时确实如此),因此请期待您的自定义标记一开始会跳动一下。您可以等到位置管理器收集到一些坐标后再将其应用到您的自定义标记,方法是等到locations.count > someNumber,但我不觉得这种方法很有吸引力。