Geolocalización y mapas en Swift: CoreLocation y MapKit para iOS/macOS

Entrenador de Python en Línea para Principiantes

Aprende Python fácilmente sin sobrecargarte de teoría. Resuelve tareas prácticas con verificación automática, recibe pistas y escribe código directamente en el navegador, sin instalar nada.

Start Course

Geolocalización y mapas en Swift: descripción general de CoreLocation y MapKit



El desarrollo de aplicaciones para iOS y macOS a menudo requiere trabajar con datos geográficos y visualización de mapas. En el ecosistema de Apple, existen dos potentes frameworks para estos fines: CoreLocation (para determinar la ubicación, geocodificación y regiones de monitoreo) y MapKit (para mostrar mapas, agregar anotaciones y trazar rutas). En este artículo, analizaremos en detalle sus capacidades y proporcionaremos ejemplos prácticos en Swift.



1. CoreLocation: obtención de coordenadas del dispositivo



CoreLocation proporciona acceso al hardware de determinación de ubicación: GPS, Wi-Fi y redes celulares. Para comenzar, es necesario importar el framework y solicitar permiso al usuario.



Configuración de permisos

En el archivo Info.plist agregue las claves:

  • NSLocationWhenInUseUsageDescription — para usar la aplicación en modo activo
  • NSLocationAlwaysAndWhenInUseUsageDescription — para monitoreo en segundo plano


Ejemplo de obtención de la ubicación actual

import CoreLocation

class LocationManager: NSObject, CLLocationManagerDelegate { private let manager = CLLocationManager() override init() { super.init() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBest } func requestPermission() { manager.requestWhenInUseAuthorization() } func startUpdating() { manager.startUpdatingLocation() } // MARK: - Delegate func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } print("Latitud: \\(location.coordinate.latitude), Longitud: \\(location.coordinate.longitude)") } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Error: \\(error.localizedDescription)") }}


2. MapKit: visualización de mapas y anotaciones



MapKit permite integrar mapas de Apple Maps en la aplicación. La clase principal es MKMapView. Veamos la configuración básica y la adición de marcadores.



Creación de un mapa en código

import MapKitimport SwiftUI

struct MapView: UIViewRepresentable { @Binding var region: MKCoordinateRegion func makeUIView(context: Context) -> MKMapView { let mapView = MKMapView() mapView.delegate = context.coordinator return mapView } func updateUIView(_ uiView: MKMapView, context: Context) { uiView.setRegion(region, animated: true) } // Coordinator para manejar eventos func makeCoordinator() -> Coordinator { Coordinator(self) } class Coordinator: NSObject, MKMapViewDelegate { var parent: MapView init(_ parent: MapView) { self.parent = parent } }}


Adición de una anotación (pin en el mapa)

import MapKit

class CustomAnnotation: NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D var title: String? var subtitle: String? init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) { self.coordinate = coordinate self.title = title self.subtitle = subtitle }}

// Uso:let annotation = CustomAnnotation( coordinate: CLLocationCoordinate2D(latitude: 55.7558, longitude: 37.6173), title: "Moscú", subtitle: "Plaza Roja")mapView.addAnnotation(annotation)


3. Geocodificación: conversión de dirección a coordenadas



La clase CLGeocoder permite convertir una dirección de texto en coordenadas (geocodificación directa) y viceversa (inversa).



import CoreLocation

l

Recommendations