Home > other >  Want to show zoom in zoom out on map through buttons in swiftUI
Want to show zoom in zoom out on map through buttons in swiftUI

Time:03-27

I want to add 2 buttons on a map in swiftUI Map to zoom in and out of it. I have positioned the two buttons at the bottom of the screen in a Stack inside a VStack. I need the code to make them work.

This is what I have:

import Foundation
import SwiftUI
import MapKit

struct QuakeDetail: View {
    var quake: Quake
    
    @State private var region : MKCoordinateRegion
    init(quake : Quake) {
        self.quake = quake
        _region = State(wrappedValue: MKCoordinateRegion(center: quake.coordinate,
                                                         span: MKCoordinateSpan(latitudeDelta: 3, longitudeDelta: 3)))
    }
    var body: some View {
        ZStack {
            
            VStack {
                Map(coordinateRegion: $region, annotationItems: [quake]) { item in
                    MapMarker(coordinate: item.coordinate, tint: .red)
                } .ignoresSafeArea()
                HStack {
                    Button {
                        print ("pressed  ")
                    } label: {
                        HStack {
                            Text("map")
                            Image(systemName: "plus")
                        }
                    }.padding(5).border(Color.blue, width: 1)
                    Spacer()
                    QuakeMagnitude(quake: quake)
                    Spacer()
                    Button {
                        print ("pressed -")
                    } label: {
                        HStack {
                            Text("map")
                            Image(systemName: "minus")
                        }
                    }.padding(5).border(Color.blue, width: 1)
                    
                }.padding()
                Text(quake.place)
                    .font(.headline)
                    .bold()
                Text("\(quake.time.formatted())")
                    .foregroundStyle(Color.secondary)
                Text("\(quake.latitude)   \(quake.longitude)")
                
                
            }
        }
    }    
}

CodePudding user response:

You have to operate with span parameter of MKCoordinateRegion for that (the less value the more zoomed area), like (demo zoom on 10%):

Button("Zoom In") {
    region.span.latitudeDelta *= 0.9
    region.span.longitudeDelta *= 0.9
}

Tested with Xcode 13.2 / iOS 15.2

  • Related