Swift 5:如何在带有坐标的点击/触摸时在 GoogleMap 上添加标记?

问题描述

我正在学习适用于 iOS 的 GoogleMap-SDK,在此过程中我确实搜索了上述问题并找到了令人满意的答案,但没有找到实际有用的答案。

E.G. :Swift 3 google map add markers on touch

添加标记,但没有地名或地点详细信息,没有标记就没有那么有用,为此我必须搜索其他答案才能从坐标中获取地址

所以,在这里我结合了这两个答案,以节省开发人员的时间并使 Marker 更实用。

解决方法

适用于 Swift 5.0+

首先,确保您已将 GMSMapViewDelegate 委托添加到您的 ViewController 类

为此我们不需要 UILongPressGestureRecognizerUITapGestureRecognizerGMSMapViewDelegate 为此提供了方便的默认方法。

///This default function fetches the coordinates on long-press on `GoogleMapView`
func mapView(_ mapView: GMSMapView,didLongPressAt coordinate: CLLocationCoordinate2D) {
     
     //Creating Marker
     let marker = GMSMarker(position: coordinate)
    
     let decoder = CLGeocoder()

     //This method is used to get location details from coordinates
     decoder.reverseGeocodeLocation(CLLocation(latitude: coordinate.latitude,longitude: coordinate.longitude)) { placemarks,err in
        if let placeMark = placemarks?.first {

            let placeName = placeMark.name ?? placeMark.subThoroughfare ?? placeMark.thoroughfare!   ///Title of Marker
            //Formatting for Marker Snippet/Subtitle       
            var address : String! = ""
            if let subLocality = placeMark.subLocality ?? placeMark.name {
                address.append(subLocality)
                address.append(",")
            }
            if let city = placeMark.locality ?? placeMark.subAdministrativeArea {
                address.append(city)
                address.append(",")
            }
            if let state = placeMark.administrativeArea,let country = placeMark.country {
                address.append(state)
                address.append(",")
                address.append(country)
            }

            // Adding Marker Details
            marker.title = placeName
            marker.snippet = address
            marker.appearAnimation = .pop
            marker.map = mapView
        }
    }
}

希望有帮助!!!

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...