UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 78: MapView doesn't update when centerCoordinate changes

Forums > 100 Days of SwiftUI

I am working on the MapKit challenge on Day 78 and I've hit a stumbling block. I've got the following code, where contact.location is of the type CLLocationCoordinate2D?. When the view appears I want to run the function, which checks whether the contact has an associated location, and then should add an annotation for that contact to the view and also move the map to center on that annotation. The first part works fine, but the second part doesn't, and I don't understand why since the view should (I think) respond to the state changing. Can anyone help?

import MapKit
import SwiftUI

struct NameDetailView: View {
    var contact: Contact
    @State private var centerCoordinate = CLLocationCoordinate2D()
    @State private var selectedPlace: MKPointAnnotation?
    @State private var showingPlaceDetails = false
    @State private var locations = [MKPointAnnotation]()
    @State private var showingMapView = false

    var body: some View {
        VStack {
            Image(uiImage: contact.image!)
                .resizable()
                .scaledToFit()
            HStack {
                Spacer()
                Text("\(contact.name)")
                    .font(.title)
                Spacer()
            }
            Spacer()

            if showingMapView {
                MapView(centerCoordinate: $centerCoordinate, selectedPlace: $selectedPlace, showingPlaceDetails: $showingPlaceDetails, annotations: locations)
            } else {
                Text("Location unknown")
            }

        }
        .onAppear(perform: moveToContactLocation)
    }

    func moveToContactLocation() {
        guard let contactLocation = contact.location else {
            print("No contact location")
            return
        }
        let contactAnnotation = MKPointAnnotation()
        contactAnnotation.title = contact.name
        contactAnnotation.coordinate = contactLocation

        self.locations.append(contactAnnotation)
        self.centerCoordinate.latitude = contactLocation.latitude
        self.centerCoordinate.longitude = contactLocation.longitude

        self.showingMapView = true
    }

}

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.