Created
April 21, 2023 09:49
-
-
Save athurg/9bc563c3ea30d080462f99e7fdb51752 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import MapKit | |
struct Point: Identifiable { | |
var id = UUID() | |
var latitude, longitude: Double | |
func coordinate() -> CLLocationCoordinate2D { | |
CLLocationCoordinate2D(latitude: latitude, longitude: longitude) | |
} | |
} | |
let defaultMapCenter = CLLocationCoordinate2D(latitude: 30.551, longitude: 104.07) | |
let defaultMapRegion = MKCoordinateRegion(center: defaultMapCenter, latitudinalMeters: 1000, longitudinalMeters: 10000) | |
let defaultPoints = [ | |
Point(latitude: defaultMapCenter.latitude+0.01, longitude: defaultMapCenter.longitude+0.01), | |
Point(latitude: defaultMapCenter.latitude+0.02, longitude: defaultMapCenter.longitude+0.02), | |
Point(latitude: defaultMapCenter.latitude+0.03, longitude: defaultMapCenter.longitude+0.03), | |
Point(latitude: defaultMapCenter.latitude+0.04, longitude: defaultMapCenter.longitude+0.04), | |
] | |
struct ContentView: View { | |
@State var mapRegion = defaultMapRegion | |
@State var annotations: [Point] = defaultPoints | |
var body: some View { | |
VStack{ | |
Map(coordinateRegion: $mapRegion, annotationItems: annotations) { point in | |
//使用MapMarker是不会报错的 | |
MapMarker(coordinate: point.coordinate(),tint: .red) | |
//使用MapAnnotation,一旦地图发生变化,比如随意拖动下,会大量的报下面的错误 | |
//Publishing changes from within view updates is not allowed, this will cause undefined behavior | |
// MapAnnotation(coordinate: point.coordinate()) { | |
// Rectangle().stroke(Color.blue).frame(width: 20, height: 20) | |
// } | |
} | |
Map(coordinateRegion: $mapRegion, annotationItems: annotations) { point in | |
MapAnnotation(coordinate: point.coordinate()) { | |
Rectangle().stroke(Color.blue).frame(width: 20, height: 20) | |
} | |
} | |
} | |
} | |
} | |
struct DemoView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment