Search code examples
iosswiftmapboxswift4.2

how do i get the latitude and longitude from struct and show them on mapbox Swift


I'm getting data from API and I need an array of latitude and longitude to show all the locations on the map (I'm using Mapbox for the map)

func getdata(){
    
print("meter is \(mapMeter)")
    
var semaphore = DispatchSemaphore (value: 0)

let parameters = "{\n    \"latitude\" : \"41.76484\",\n\"longitude\" : \"123.3968636\",\n\"dist\": \"\(mapMeter)\"\n}"
let postData = parameters.data(using: .utf8)

var request = URLRequest(url: URL(string: "http://app.freewayfinder.com/api/locations")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  guard let data = data else {
    print(String(describing: error))
    semaphore.signal()
    return
  }

    let getlocation = try? JSONDecoder().decode(Response.self, from: data)
    guard let locations = getlocation else {return}
    self.locations = locations.message
    self.collectionView.reloadData()
  semaphore.signal()
}

task.resume()
semaphore.wait()
    }

struct for location:

struct Response : Decodable {
let success : Bool
let code : Int
let message : [location]
}

struct location : Decodable{
let id : Int
let name : String
let img : String
let latitude : String
let longitude : String
let city : String
let country : String
let created_at : String
let updated_at : String

}

kindly help me out with this I want to show allocation on the map


Solution

  • You can set location from array in Map like this

    for locationStruct in self.locations
    {
        let annotation = MGLPointAnnotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: Double(locationStruct.latitude), longitude: Double(locationStruct.longitude))
        annotation.title = locationStruct.name
        annotation.subtitle = "Your Subtitle"
        self.mapView.addAnnotation(annotation)
    
    }