Let's_Create
Let's_Create

Reputation: 3613

How to Update Google Maps Marker Image when tap on the marker

I want to change the marker icon and show info window when tapped on the marker. My question here is how to change the marker icon?

I have stored the google maps instance and tried updating it my setting iconView property of that marker

func setUpMarker() {
        let markerView = UIImageView(image: UIImage(named: "pinImage"))
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lng)
        marker.iconView = markerView

        storeMarker = marker
    }

Method to update marker

func updateMarker() {
        let markerView = UIImageView(image: UIImage(named: "circleImage"))
        storeMarker.iconView = markerView
    }

But, this adds a new icon on the previous icon.

Upvotes: 2

Views: 1825

Answers (2)

Daniel T.
Daniel T.

Reputation: 33967

In the comments you asked how to deselect the currently selected marker. That's a bit more involved. I do it something like this:

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    // `markers` is an array of all the markers currently on the map.
    markers.forEach {
        ($0.iconView as! UIImageView).image = #imageLiteral(resourceName: "unselected-pin")
    }
    (marker.iconView as! UIImageView).image = #imageLiteral(resourceName: "selected-pin")
    return true
}

Previous Answer

func mapView(_ mapView: GMSMapView, didTapMarker marker: GMSMarker) -> Bool {
    print("tapped on marker")
    if storeMarker == marker {
        (marker.iconView as! UIImageView).image = #imageLiteral(resourceName: "circleImage")
    }
    return true
}

Upvotes: 3

Milan
Milan

Reputation: 141

You need to implement Google map delegate method

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {}

 func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {}

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

Upvotes: 0

Related Questions