4

SwiftUI MapKit Tutorial - iOScreator

 3 years ago
source link: https://www.ioscreator.com/tutorials/swiftui-mapkit-tutorial
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
SwiftUI MapKit Tutorial

In SwiftUI a Map view can be displayed showing a map inside the main view. Using Map view, the portion of the map that is displayed on the screen is referred to as the region. The region is defined by a center location and a span of the surrounding area to be displayed. In this tutorial we will display a portion of the city London. This tutorial is built for iOS 14 with Xcode 12 which can be download at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIMapKitTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbox and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Import the MapKit framework.

import MapKit

change the ContentView to

struct ContentView: View {
    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.50007773, longitude: -0.1246402) , span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
    
    var body: some View {
        Map(coordinateRegion: $region)
            .edgesIgnoringSafeArea(.all)
    }
}

The latitude and longitude of the city of London is defined using the CLLocationCoordinate2d struct. The span value is made relative small, so a big portion of London is visible. The MKCoordinateRegion method defines the visible region. With the Map view the assigned region is displayed.

Go to the preview Window and select the Live Preview button. The Preview will look like this.

The source code of the SwiftUIMapKitTutorial can be downloaded at the ioscreator repository on Github.

Related Articles


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK