Get LAT and LONG from tapped overlay in Google Maps

纵饮孤独 提交于 2019-12-20 04:07:17

问题


When a user taps an overlay, the following code is triggered:

func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) {


    }

I wonder if we can extract the exact LAT and LONG coordinates of the overlay that has been tapped?

Thanks!


回答1:


To solve this we need the 2 methods together, So I combined them in a way I hope it will help in this issue:

func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) {
    print(overlay)
}

func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
    print(coordinate)

    for polyline in polylines {
        if GMSGeometryIsLocationOnPath(coordinate, polyline.path!, true) {
            self.mapView(mapView, didTap: polyline)
        }
    }
    for polygon in polygons {
        if GMSGeometryContainsLocation(coordinate, polygon.path!, true) {
            self.mapView(mapView, didTap: polygon)
        }
    }
}

if the user clicked at coordinate we will deal with this, Then check if this coordinate is contained in any Polyline or Polygon we had defined before, So we fire the event didTap overlay for that overlay.

Make sure to make polylines and polygons isTappable = false

And but in mind this event will be fired for every overlay tapped even though if they are overlaped, You can put return when the if success to take the first overlay only




回答2:


You can use didTapAt delegate method for the same.

@wajih, for you did the method didTapAt was called when you tap on landmark names or titles? For me it's not getting called. For my case the landmark title is above the polygon and the didTapAt method is not getting called, but if i set tappable to true then didTap(overlay) is called perfectly.




回答3:


If you just want to get the exact coordinates wherever you tapped whether on Overlay or not, then there is another delegate of GMSMapViewDelegate which is called whenever we tap on GoogleMaps. In this delegate you can get the exact coordinates where you tapped on map irrespective of tapping on an overlay.

Swift 3.0

 func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
        print(coordinate.latitude)
        print(coordinate.longitude)
    }

If you want to get the coordinate only on tapping marker, then use this delegate method

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
        print(marker.position.latitude)
        print(marker.position.longitude)
        return true
    }

Make sure to make your overlay as non-tappable

overlay.isTappable = false

For reference see here



来源:https://stackoverflow.com/questions/39977363/get-lat-and-long-from-tapped-overlay-in-google-maps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!