TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Use var for lat/lon Map cameraPosition

Forums > SwiftUI

Hi communities

I want to define cameraPosition Latitude and longitude for map in view by 2 var ( LatTo and LonTo ) initialised by call a view

aff(LatTo: 50,LonTo: 6)
struct aff: View {

    var LatTo: String = ""
    var LonTo: String = ""

    init(LatTo: String,LonTo: String) {
        self.LatTo = LatTo
        self.LonTo = LonTo

    }

    @State var cameraPosition: MapCameraPosition = .region(MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: Double(LatTo)!, longitude: Double(LonTo)!), span: MKCoordinateSpan(latitudeDelta: 0.25, longitudeDelta: 0.25)))

    var body: some View {

    ...

But Xcode return

Cannot use instance member 'LatTo' within property initializer; property initializers run before 'self' is available
Cannot use instance member 'LonTo' within property initializer; property initializers run before 'self' is available

I understand the problem i can't use dynamic LatTo and LonTo for define cameraPosition, but if possible i want to use this structure, i begin in swift and i don't know to solve it

Thanks

2      

You will need to setup the cameraPosition within the view init. Because it's a State var, the syntax is a little different.

I haven't used MapKit much, so I'm not sure I have the MapCameraPosition.region bit right, but this is how you work with a State var in the view init.

struct aff: View {

  var LatTo: String = ""
  var LonTo: String = ""

  @State var cameraPosition: MapCameraPosition

  init(LatTo: String,LonTo: String) {
    self.LatTo = LatTo
    self.LonTo = LonTo

    let newCameraPosition = MapCameraPosition.region(MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: Double(LatTo)!, longitude: Double(LonTo)!), span: MKCoordinateSpan(latitudeDelta: 0.25, longitudeDelta: 0.25)))

    _cameraPosition = State(initialValue: newCameraPosition)

  }

  var body: some View {

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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

Reply to this topic…

You need to create an account or log in to reply.

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.