pod 'GoogleMaps' # 显示基本的定位功能
pod 'GooglePlaces' # 实现搜索功能,官方文档叫做地点自动完成
pod 'GooglePlacePicker' # 是实现获取某个POI的的详细信息,比如名字、详细地址、路线等)
使用
加载地图
lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: 39.914245, longitude: 116.405338, zoom: 6) //默认初始化一个定位
let view = GMSMapView(frame: .zero, camera: camera)
view.mapType = .normal
view.accessibilityElementsHidden = false
view.isMyLocationEnabled = true
view.isBuildingsEnabled = true
view.settings.compassButton = true
}()
地图拖动结束后回调
extension YYMapViewManager:GMSMapViewDelegate{
func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
print("--->")
locationDragged.accept(true)
}
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
print("--->2")
if locationDragged.value{
print("changed position: \(mapView.camera.target)")
}
}
}
添加标记点 GMSMarker
// 加入终点
let destionMarker = GMSMarker(position: CLLocationCoordinate2D(latitude: destination.lat, longitude: destination.lon))
destionMarker.title = String(format: localized("大约行驶%ld分钟"), 0)
destionMarker.appearAnimation = .pop
destionMarker.map = mapView
标记点额外信息
[图片上传失败...(image-da1b1d-1667009969919)]
需要实现GMSMapViewDelegate
的 markerInfoWindow
方法
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
if marker.title == nil{return nil}
if marker.title!.contains(localized("等待应答")){
//marker.tracksViewChanges = true
//marker.tracksInfoWindowChanges = true
return hintInMapView
}else{
return nil
}
}
需要注意的是;为了性能,默认情况下自定义的view
初始化完成后是不会再进行任何绘制的,包括label.text
,动画等;可以理解为view
都是静态的,如果要进行改变,需要 marker.tracksInfoWindowChanges
为true
,google建议是,改变完成后,需要再将tracksInfoWindowChanges
设置为false
。
移动地图在Bounds范围内
let bounds = GMSCoordinateBounds(coordinate: startPointAnnotation.position, coordinate: destinationAnnotation.position)
let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsets.zero)
self.mapView.moveCamera(update)
使得地图不可拖动
mapView.settings.scrollGestures = false
mapView.settings.zoomGestures = false
绘制线段
let path = GMSMutablePath()
for coordinate in self.lineCoordinates {
path.add(CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude))
}
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 6.0
polyline.strokeColor = UIColor(hexString: "#00C47A")!
polyline.geodesic = true
polyline.map = self.mapView
self.polyline = polyline
你可能用到通过 Directions API 查询路线: /directions/json
此时反馈的点不会吸附道路进行绘制,还需要进一步的优化,来得到更优的路线
沿实际道路: /snapToRoads/
问题收集
1.打开地图空白,但有定位点点击查看>>>
检查是否启用了“Google Maps SDK for iOS”。如果不是,启用它。
[图片上传失败...(image-c05ea9-1667009969919)]