Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

ios - 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 = "{
    "latitude" : "41.76484",
"longitude" : "123.3968636",
"dist": "(mapMeter)"
}"
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

question from:https://stackoverflow.com/questions/65914128/how-do-i-get-the-latitude-and-longitude-from-struct-and-show-them-on-mapbox-swif

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...