create an app to retrieve a list of locations and display on a map in swift

To create an app to retrieve a list of locations and display on a map, we can use MapKit to display the map, and CoreLocation to access the device's location. We can use an API like Yelp or Google Places to retrieve the list of locations. Here is an example of how to do this in Swift:

  1. Set up MapView and LocationManager
main.swift
import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    var mapView: MKMapView!
    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Initialize mapView
        mapView = MKMapView(frame: view.frame)
        mapView.showsUserLocation = true
        mapView.delegate = self
        view.addSubview(mapView)

        // Initialize locationManager
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            locationManager.requestLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let userLocation = locations.last {
            let region = MKCoordinateRegion(center: userLocation.coordinate, latitudinalMeters: 10000, longitudinalMeters: 10000)
            mapView.setRegion(region, animated: true)
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
    
}
1361 chars
43 lines
  1. Get location data from API
main.swift
import Alamofire
import SwiftyJSON

let url = "https://api.yelp.com/v3/businesses/search?term=food&location=San+Francisco"

let headers: HTTPHeaders = [
    "Authorization": "Bearer ACCESS_TOKEN",
    "Accept": "application/json"
]

AF.request(url, headers: headers).responseJSON { response in
    switch response.result {
    case .success(let value):
        let json = JSON(value)
        let businesses = json["businesses"].arrayValue
        
        for business in businesses {
            let name = business["name"].stringValue
            let latitude = business["coordinates"]["latitude"].doubleValue
            let longitude = business["coordinates"]["longitude"].doubleValue
            
            let annotation = MKPointAnnotation()
            annotation.title = name
            annotation.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
            mapView.addAnnotation(annotation)
        }
    case .failure(let error):
        print(error.localizedDescription)
    }
}
1024 chars
31 lines

This code sends a request to Yelp API to retrieve a list of businesses that match the term "food" and location "San Francisco". We parse the JSON response using SwiftyJSON, extract the name, latitude, and longitude of each business, and create an MKPointAnnotation with these values. We add the annotation to the mapView.

This is just a basic example. You can customize it to suit your requirements.

related categories

gistlibby LogSnag