我在mapView中添加多个标记时遇到了麻烦,但是我总是最后显示一个标记,而最后一个标记是我不知道为什么。 这样做的目的是获取包含经度和纬度的数据并添加这些标记,我试图将其静态化,但是我可以显示多个标记
我创建了一个添加新标记的函数,并在viewDidLoad中调用它 `覆盖func viewDidLoad(){ super.viewDidLoad()
AddMarker(title: "pala", snippet: "nanana", latitude: 35.741522, longitude: 9.805937)
AddMarker(title: "pala", snippet: "nanana", latitude: 36.89939467218524, longitude: 10.187976658321267)
}
private func AddMarker(title:String , snippet:String , latitude:Double , longitude:Double){
var title = title
var snippet = snippet
var latitude = latitude
var longitude = longitude
let camera = GMSCameraPosition.camera(withLatitude: latitude, longitude: longitude, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = mapView
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
marker.title = title
marker.snippet = snippet
marker.map = mapView
}
`
答案 0 :(得分:1)
在addMarker方法之外,将GMSMapView实例创建为实例属性。然后在addMarker方法中更改它的相机位置并添加标记。
let mapView = GMSMapView()
private func addMarker(title:String, snippet:String , latitude:Double , longitude:Double){
let camera = GMSCameraPosition.camera(withLatitude: latitude, longitude: longitude, zoom: 6.0)
self.mapView.animate(to: camera)
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
marker.title = title
marker.snippet = snippet
marker.map = mapView
}
一个接一个地添加多个标记时,请勿将相机位置设置为最后一个标记位置的动画。要在地图视图中显示所有标记,您可以使用GMSCoordinateBounds
let mapView = GMSMapView()
var bounds = GMSCoordinateBounds()
override func viewDidLoad() {
super.viewDidLoad()
addMarker(title: "pala", snippet: "nanana", latitude: 35.741522, longitude: 9.805937)
addMarker(title: "pala", snippet: "nanana", latitude: 36.89939467218524, longitude: 10.187976658321267)
}
private func addMarker(title:String, snippet:String , latitude:Double , longitude:Double){
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
marker.title = title
marker.snippet = snippet
marker.map = mapView
bounds = bounds.includingCoordinate(marker.position)
let update = GMSCameraUpdate.fit(bounds, withPadding: 50)
mapView.animate(with: update)
}