Search code examples
iosgoogle-mapsgoogle-maps-api-3

iOS Swift Google Maps - mapView didTapMarker not working?


So I'm learning and getting my head around swift/google maps API. However, no matter what I try, when I tap on the marker I cannot get the print statement to appear in the console.

Tapping the marker displays the marker Name, however it never prints. I've tried a few variations of the private func found online, but maybe I'm missing something more fundamental here...

import UIKit
import GoogleMaps

class ViewController: UIViewController, GMSMapViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        struct MarkerStruct {
            let name: String
            let lat: CLLocationDegrees
            let long: CLLocationDegrees
        }

        let markers = [
            MarkerStruct(name: "Food Hut 1", lat: 52.649030, long: 1.174155),
            MarkerStruct(name: "Foot Hut 2", lat: 52.649030, long: 1.174185),
        ]

        let camera = GMSCameraPosition.camera(withLatitude: 52.649030, longitude: 1.174155, zoom: 14)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        mapView.delegate = self
        self.view = mapView

        for marker in markers {
            let position = CLLocationCoordinate2D(latitude: marker.lat, longitude: marker.long)
            let locationmarker = GMSMarker(position: position)
            locationmarker.title = marker.name
            locationmarker.map = mapView
        }
    }

    private func mapView(mapView: GMSMapView, didTapMarker marker: GMSMarker) {
        print("Marker tapped")
    }

}

Solution

  • You are using an old method name and you also need remove the private keyword, that is why your delegate method is not called

    now is

    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
         print("Marker tapped")
         return true 
    }
    

    working now