Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index from GMSMarker tapped?

How to detect which marker was pressed on a map. I have few markers on map and class Marker in markers array downloaded from API, that contains some data.

for example i have data like this

[States(name: "text1", long: 110.42400399999997,lat: -7.0343237999999992), 
States(name: "text2", long: 110.42769829999997, lat: -7.0856947999999997), 
States(name: "text3", long: 110.42922440000007, lat: -7.3250846999999997), 
States(name: "text4", long: 117.11625830000003, lat: -0.50436380000000003), 
States(name: "text5", long: 110.43093620000002, lat: -7.0730081999999994)]

if i tap on marker that contain data 1 (States(name: "text1", long: 110.42400399999997,lat: -7.0343237999999992))

How do i get index 0. and if i tap on marker that contain data 2, How do i get index 1?

like image 594
Ariel Gemilang Avatar asked Dec 28 '25 05:12

Ariel Gemilang


1 Answers

So I suppose you added the markers by iterating through the array like this:

for state in states { // assuming states is the array you showed in the question
    let marker = GMSMarker(position: CLLocationCoordinate2D(latitude: state.lat, longitude: state.long))
    // configure the marker...
    marker.map = mapView
}

The idea is that you add the markers to an array as well, just after you created it. Since you created the markers in the order of the data, each item in the array containing the markers corresponds to the data at the same index.

Let's declare the array of markers at class level:

var markers = [GMSMarker]()

Then in the for loop above, add the marker to markers:

markers.append(marker)

Now you can find out which datum is tapped just by:

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    if let index = markers.index(of: marker) {
        let tappedState = states[index]
    }
}
like image 108
Sweeper Avatar answered Dec 30 '25 20:12

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!