top of page
Writer's pictureHui Wang

34. SwiftUI: Introducing Map and MapPin

Today I will show you how to use SwiftUI's Map and MapPin.


Steps:

  • First, import the MapKit framework.

  • Then define a struct as the type of the elements in the MapPin array

  • Add an id property to conform to the Identifiable protocol.

  • Then add a property as a map pin on the map.

import MapKit

struct IdentifiableMapPin: Identifiable {
    var id: Int
    var mapPin: MapPin
}

  • Initialize a MKCoordinateRegion property as the coordinate region that the map needs to display.

@State var coordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 59.3273939, longitude: 18.0627908), span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))

  • Add an array property for all map pins on the map.

@State var mapPins: [IdentifiableMapPin] = []

  • Creates a Map that displays geographic information for the specified area based on two parameters.

  • After the Map is displayed, display the map pins on the map.

  • Initialize a MapPin and set its geographic location.

  • Then add MapPin to the array so that the app can display all map pins on the map.

Map(coordinateRegion: $coordinateRegion, annotationItems: mapPins) { identifiableMapPin in
    identifiableMapPin.mapPin
}.onAppear {
    let mapPin1 = MapPin(coordinate: CLLocationCoordinate2D(latitude: 59.3273939, longitude: 18.0627908))
    let mapPin2 = MapPin(coordinate: CLLocationCoordinate2D(latitude: 59.3257847, longitude: 18.0713309))
    
    mapPins.append(IdentifiableMapPin(id: mapPins.count, mapPin: mapPin1))
    mapPins.append(IdentifiableMapPin(id: mapPins.count, mapPin: mapPin2))
}


Source Code:

import SwiftUI
import MapKit

struct IdentifiableMapPin: Identifiable {
    var id: Int
    var mapPin: MapPin
}

struct ContentView: View {
    @State var coordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 59.3273939, longitude: 18.0627908), span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
    
    @State var mapPins: [IdentifiableMapPin] = []
        
    var body: some View {
        Map(coordinateRegion: $coordinateRegion, annotationItems: mapPins) { identifiableMapPin in
            identifiableMapPin.mapPin
        }.onAppear {
            let mapPin1 = MapPin(coordinate: CLLocationCoordinate2D(latitude: 59.3273939, longitude: 18.0627908))
            let mapPin2 = MapPin(coordinate: CLLocationCoordinate2D(latitude: 59.3257847, longitude: 18.0713309))
            
            mapPins.append(IdentifiableMapPin(id: mapPins.count, mapPin: mapPin1))
            mapPins.append(IdentifiableMapPin(id: mapPins.count, mapPin: mapPin2))
        }
    }
}

 

Follow me on:

Comments


bottom of page