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

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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.