作者:subingyi84 | 来源:互联网 | 2023-02-05 16:25
如何检测在地图上按下了哪个标记。从API下载的markers数组中,map和class Marker上的标记很少,其中包含一些数据。
例如我有这样的数据
[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)]
如果我点击包含数据的标记1(States(name: "text1", long: 110.42400399999997,lat: -7.0343237999999992)
)
如何获取索引0。如果我点击包含数据2的标记,如何获取索引1?
1> Sweeper..:
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]
}
}