我需要在地图视图中添加多个标记。如何使用swiftui在同一个地图视图中添加多个标记?
这是我的代码。
import SwiftUI
import UIKit
import GoogleMaps
struct MapView: UIViewRepresentable {
let coordinate: CLLocationCoordinate2D?
let marker : GMSMarker = GMSMarker()
func makeUIView(context: Self.Context) -> GMSMapView {
let camera = GMSCameraPosition.camera(withLatitude: coordinate.latitude, longitude: coordinate.longitude, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
return mapView
}
func updateUIView(_ mapView: GMSMapView, context: Self.Context) {
marker.position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
marker.title = "XYZ"
marker.snippet = "ABCD"
marker.map = mapView
}
}
这是我的示例。
struct MapView: UIViewRepresentable {
let coordinate: CLLocationCoordinate2D
let cities = [
[
"name": "Yangon",
"lat": 16.8409,
"long": 96.1735
],
[
"name": "Mandalay",
"lat": 21.9588,
"long": 96.0891
]
]
func makeUIView(context: Self.Context) -> GMSMapView {
let camera = GMSCameraPosition.camera(withLatitude: coordinate.latitude, longitude: coordinate.longitude, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
return mapView
}
func updateUIView(_ mapView: GMSMapView, context: Self.Context) {
for city in cities {
let marker : GMSMarker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: city["lat"] as! CLLocationDegrees, longitude: city["long"] as! CLLocationDegrees)
marker.title = city["name"] as? String
marker.snippet = "Welcome to \(city["name"] as! String)"
marker.map = mapView
}
}
}