Get LAT and LONG from tapped overlay in Google Map

2019-03-01 16:36发布

问题:

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