【问题标题】:Swift 5: How to add Marker on GoogleMap on tap/touch with coordinates?Swift 5:如何在点击/触摸坐标时在 GoogleMap 上添加标记?
【发布时间】:2021-09-02 05:14:51
【问题描述】:

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

例如:Swift 3 google map add markers on touch

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

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

【问题讨论】:

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


    【解决方案1】:

    适用于 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
            }
        }
    }
    

    希望对您有所帮助!!!

    【讨论】:

    • 请注意,CLGeocoder.reverseGeocodeLocation 调用受 iOS 速率限制,可能会不一致地失败。只要你在使用谷歌地图,就应该考虑使用GMSGeocoder.reverseGeocodeCoordinate
    • @TarunTyagi,感谢您的建议..在您发表评论后,我确实尝试GMSGeocoder 来获取位置地址,我比较了两个结果....结论是苹果的 CLGeocoder 在在 GMSGeocoder 无法准确获取地名时获取地名。
    猜你喜欢
    • 2017-10-08
    • 2013-06-13
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2019-12-06
    相关资源
    最近更新 更多