【问题标题】:Swift 3 google map add markers on touchSwift 3 谷歌地图在触摸时添加标记
【发布时间】:2017-10-08 04:57:18
【问题描述】:

我在使用谷歌地图标记时遇到问题,我想将标记放在触摸上,但我不知道如何处理我尝试了几种方法,但它不起作用,然后我触摸地图没有任何反应。 pressrecognizer 好像有问题。

更新:

class MainMapController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var viewMap: GMSMapView!
var makers: [GMSMarker] = []

var locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()


    initializeTheLocationManager()
    self.viewMap.isMyLocationEnabled = true
  let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
  self.viewMap.addGestureRecognizer(longPressRecognizer)


}

  func handleLongPress(recognizer: UILongPressGestureRecognizer)
   {
if (recognizer.state == UIGestureRecognizerState.began)
{
  let longPressPoint = recognizer.location(in: self.viewMap);
  let coordinate = viewMap.projection.coordinate(for: longPressPoint )
  let marker = GMSMarker(position: coordinate)
  marker.opacity = 0.6
  marker.title = "Current Location"
  marker.snippet = ""
  marker.map = viewMap
  makers.append(marker)
    }
  }


func initializeTheLocationManager()
{
    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}


func locationManager(_ manager: CLLocationManager,      didUpdateLocations locations: [CLLocation]) {

    var location = locationManager.location?.coordinate

    cameraMoveToLocation(toLocation: location)
    locationManager.stopUpdatingLocation()     
}    
func cameraMoveToLocation(toLocation: CLLocationCoordinate2D?) {
    if toLocation != nil {
        viewMap.camera = GMSCameraPosition.camera(withTarget: toLocation!, zoom: 15)        
    }
    }

【问题讨论】:

  • viewMap 是 GMSMapView 吗?
  • 是的,你是对的
  • 我试过了,当我点击地图时没有任何反应
  • 你能告诉我更多代码吗?
  • 更新了我的问题

标签: swift google-maps google-maps-markers


【解决方案1】:

您不应该为 Google 地图手动添加手势识别器,它会自行管理交互,并有专门的委托函数来处理常见手势。

要在 GSMMapView 上长按,请确保您设置了委托

self.mapView.delegate = self

然后连接适当的委托函数

extension ViewController: GMSMapViewDelegate {
    func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
         // Custom logic here
         let marker = GMSMarker()
         marker.position = coordinate
         marker.title = "I added this with a long tap"
         marker.snippet = ""
         marker.map = mapView
    }
}

上面的代码会在你长按的位置添加一个标记,你也可以添加一个标题和sn-p,你可以看到。实际将其添加到地图的部分是marker.map = mapView

【讨论】:

  • 我试图添加这个,但是当我点击地图时没有任何反应。
  • 你在长按吗?我在这里有一个包含此代码的示例项目,它对我来说很好
  • 是的,但什么也没发生,你能给我看看吗?
  • 查看这个 git 存储库。请记住将您的 API_KEY 添加到 AppDelegate 以运行。 github.com/martinjkelly/gmaps-ios-long-tap-sample
猜你喜欢
  • 2018-07-31
  • 1970-01-01
  • 2016-06-22
  • 2011-01-11
  • 2013-06-13
  • 1970-01-01
  • 2017-10-10
  • 2016-03-16
相关资源
最近更新 更多