Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
Adding Overlay to MKMapView using OpenWeatherMap (Swift)

I have no idea where to begin.

Here's the documentation: https://openweathermap.org/api/weathermaps

Following that, and searching what I could online I tried the following, but it gives me a fatal error and never goes past that. (Note: I'm not sure what to put for the z, x, and y values either, so I left them, in addition to my API Key, blank here, but in my code I just put 1/1/1) My attempt, inserting temp_new to receive the temperature overlay:

    Service.shared.getInfoCompletionHandler(requestURL: "https://tile.openweathermap.org/map/temp_new/{z}/{x}/{y}.png?appid={myKey}") { data in
        
        if let data = data{
            var geoJson = [MKGeoJSONObject]()
            do{
                geoJson = try MKGeoJSONDecoder().decode(data)
            }
            catch{
                fatalError("Could not decode GeoJson")
            }
            
                var overlays = [MKOverlay]()
                for item in geoJson{
                    if let feature = item as? MKGeoJSONFeature{
                        for geo in feature.geometry{
                            if let polygon = geo as? MKPolygon{
                                overlays.append(polygon)
                            }
                        }
                    }
                }
                
                DispatchQueue.main.async {
                [unowned self] in
                //set to global variable
                self.overlays = overlays
                }
        }
    }

My thought process was to simply extract the overlays and then add it to the MKMapView like this:

mapView.addOverlays(self.overlays)

If its relevant, this is the completion handler I have in my Service.swift for making the API call:

//Get Info API
func getInfoCompletionHandler(requestURL: String, completion: @escaping (Data?)->Void){
    guard let url = URL(string: requestURL) else {return}
    
    URLSession.shared.dataTask(with: url) { data, response, error in
        if error == nil {
            if let data = String(data: data!, encoding: .utf8), let response = 
            response{
                print(data)
                print(response)
            }
        } else{
            if let error = error {
                print(error)
            }
        }
            completion(data)
        
    }.resume()

Am I on the right track?

Any help is appreciated, thank you!

EDIT:

After playing around I noticed I can simply parse the data as imageData with the following code:

class ViewController: UIViewController {

//Properties
var imgData = Data()
let imageView = UIImageView()

override func viewDidLoad() {
    super.viewDidLoad()
    
    //imageView frame
    view.addSubview(imageView)
    imageView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.width)
    imageView.center = view.center
    imageView.contentMode = .scaleAspectFit
    
    
    //image string
    let imgString = "https://tile.openweathermap.org/map/temp_new/0/0/0.png?appid={myKey}"
    //convert string to url object (needed to decode image data)
    let imgUrl = URL(string: imgString)
    //convert url to data
    self.imgData = try! Data(contentsOf: imgUrl!)
    //set to imageView
    self.imageView.image = UIImage(data: self.imgData)
}


}

Giving me this result:

enter image description here

So now the only question that remains is how do I add this imageView as an overlay on the mapView?

over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda