1. Home
  2. Getting Started
  3. Draw nearby parking areas on a map using MapKit

Draw nearby parking areas on a map using MapKit

This example demonstrates how to request parking data for an area using the AIPARK SDK and render it on a map using Apple MapKit.

Requirements to complete the project:

  • You will need to integrate the AIPARK SDK. You can find the SDK and setup instructions on GitHub.
  • You also need an API key. After signing up for AIPARK studio, you can grab your API here in your personal account settings page.

Don’t forget to add the required permissions as listed in the SDK setup guide to your app’s Info.plist file.
For this example, one ViewController with a map and two class extensions are required:

MapView

import UIKit
import AIPARKSDK
import MapKit


class ViewController: UIViewController {

    let aiparkcontroller = AIPARK(apikey: "Your APIkey")
    let annotationColor = "#0099ff"
    let mapView = MKMapView()

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.delegate = self
        let ownPosition = CLLocationCoordinate2D(latitude: 52.26116943359375, longitude: 10.55026832736453)
        centerMapOnLocation(location: ownPosition)
        
        let tileValues = aiparkcontroller.getTileForCoordinates(latitude: ownPosition.latitude, longitude: ownPosition.longitude, zoom: 16)
        let tile = Tile(x: tileValues.x, y: tileValues.y)
        
        let request = ParkingAreaRequest(tiles: [tile])
        aiparkcontroller.getParkingAreas(request: request) { (parkingareas) in
            for entry in parkingareas {
                if entry.shapeType == .LineString {
                    let line = MKPolyline(coordinates: entry.outlinePolygon[0], count: entry.outlinePolygon[0].count)
                    DispatchQueue.main.async {
                        self.mapView.addOverlay(line)
                    }
                }
                let area = MKPointAnnotation()
                area.title = "\(entry.capacity!) spots"
                area.subtitle = entry.name ?? ""
                area.coordinate = entry.center!
                
                DispatchQueue.main.async {
                    self.mapView.addAnnotation(area)
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        mapView.frame = self.view.bounds
        view.addSubview(mapView)
    }
    
    func centerMapOnLocation(location: CLLocationCoordinate2D) {
        let regionRadius: CLLocationDistance = 1000
        let coordinateRegion = MKCoordinateRegion(center: location,
                                                  latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
        mapView.setRegion(coordinateRegion, animated: true)
    }

}

MapView extension

// Extension for MapViewDelegate
extension ViewController: MKMapViewDelegate {
    
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer! {
        if (overlay is MKPolyline) {
            let polylineRender = MKPolylineRenderer(overlay: overlay)
            polylineRender.strokeColor = UIColor(hex: annotationColor).withAlphaComponent(0.7)
            polylineRender.lineWidth = 3
            return polylineRender
        }
        return nil
    }
    
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        guard let annotation = annotation as? MKPointAnnotation else { return nil }
        let identifier = "marker"
        var view: MKMarkerAnnotationView
        if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
            as? MKMarkerAnnotationView {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {
            view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            view.canShowCallout = true
            view.calloutOffset = CGPoint(x: -5, y: 5)
            view.markerTintColor = UIColor(hex: annotationColor)
        }
        return view
    }
}

UIColor convenience extension

// Extension for converting from hex
extension UIColor {
    public convenience init(hex: String) {
        let hexString = hex + "ff"
        let r, g, b, a: CGFloat
        
        if hexString.hasPrefix("#") {
            let start = hexString.index(hexString.startIndex, offsetBy: 1)
            let hexColor = String(hexString[start...])
            
            if hexColor.count == 8 {
                let scanner = Scanner(string: hexColor)
                var hexNumber: UInt64 = 0
                
                if scanner.scanHexInt64(&hexNumber) {
                    r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                    g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                    b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                    a = CGFloat(hexNumber & 0x000000ff) / 255
                    
                    self.init(red: r, green: g, blue: b, alpha: a)
                    return
                }
            }
        }
        self.init(red: 0, green: 113/255, blue: 188/255, alpha: 1)
        return
    }
}
Updated on January 7, 2019

Was this article helpful?

Related Articles

Bitnami