如何允许用户在地图上放置标记?

How to allow user to place markers on map?

我有一个关于标记的小问题。我应该怎么做才能让用户在我的 google 基于地图的应用程序上放置他自己的标记?

有多种方法可以做到这一点。其中之一是在用户长按地图时添加标记。要检测长按,请实现此委托方法:

func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
    let marker = GMSMarker(position: coordinate)
    // marker.isDraggable = true
    // marker.appearAnimation = kGMSMarkerAnimationPop
    marker.map = mapView
    // marker.icon = GMSMarker.markerImage(with: UIColor.blue)
}

注释掉的行是可选的,因为它们只是设置标记的自定义属性。您还可以自定义更多内容。

此外,如果您还没有这样做,请将 GMSMapViewDelegate 添加到您的视图控制器 class' 声明:

class YourViewController: UIViewController, GMSMapViewDelegate {

并将 self 分配给 delegate 属性:

    let camera = GMSCameraPosition.camera(withLatitude: 0, longitude: 0, zoom: 3)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    mapView.isMyLocationEnabled = true
    view = mapView

    mapView.delegate = self // add this line!

或者,您可以在其他事件发生时添加标记。例如,您可以在用户点击 UIBarBUttonItemUIButton 时添加标记。全取决于你!但是添加按钮的过程基本上就是这两行:

let marker = GMSMarker(position: coordinate)
marker.map = mapView 
// mapView is the map that you want to add the marker to. If you are doing this outside a delegate method, use self.view

您也可以考虑将标记添加到一个集合中,以便以后修改它们。