使用SwiftUI将单个图钉添加到Mapkit

时间:2019-09-16 17:16:53

标签: ios mapkit swiftui

如何使用Xcode 11 GM / SwiftUI在地图上添加简单的图钉。

我的代码如下(这里显示了以坐标为中心的地图),但是我只想在其中显示其他坐标的一针。

import SwiftUI
import MapKit

struct ContentView: UIViewRepresentable {
    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }

    func updateUIView(_ view: MKMapView, context: Context) {
        let coordinate = CLLocationCoordinate2D(
            latitude: 34.011_286, longitude: -116.166_868)
        let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        view.setRegion(region, animated: true)



    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

谢谢您的任何建议。

1 个答案:

答案 0 :(得分:1)

更新您的代码:

struct ContentView: UIViewRepresentable {


    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }

    func updateUIView(_ view: MKMapView, context: Context) {


        // 1 
        view.mapType = MKMapType.standard // (satellite)

        // 2
        let mylocation = CLLocationCoordinate2D(latitude: -6.863190,longitude: -79.818250)

        // 3
        let coordinate = CLLocationCoordinate2D(
            latitude: -6.864138, longitude: -79.819634)
        let span = MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        view.setRegion(region, animated: true)

        // 4
        let annotation = MKPointAnnotation()
        annotation.coordinate = mylocation

        annotation.title = "My Location"
        annotation.subtitle = "Visit us soon"
        view.addAnnotation(annotation)






    }
}

Preview