Search code examples
iosswiftmapkitmkmapview

Plotting a Specific Location on map view with latitude and longitude


I want to plot a specific point on the map having the lat and lon from an api.

Program flow:

  1. Get LAT & LON from api (done)
  2. Ping api again via timer after every 5 seconds to get the latest location (done)
  3. Plot location with retrieved LAT & LON on map

The issue is every code on the net has to do with 2 points, so user loc and destination loc. I cant seem to get it to work without user loc. I have however coded this to plot the location. However, with this when I touch the map, the map zooms out. Another issue is when I get another point the previous one also remains on the screen. (for testing purpose I hard coded the lat and lon but when I connect the api code that refreshes, prior points remain and the map code is the same as this. The lat and lon are passed via func parameters in createAnnotation().)

My code:

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self // or connect in storyboard
        createAnnotation()
    }

    func createAnnotation(){
        let annotations = MKPointAnnotation()
        annotations.coordinate = CLLocationCoordinate2D(latitude: 41.87369, longitude: -87.813293)
        mapView.addAnnotation(annotations)
    }}


How Do I plot the coordinates properly? and then delete the prior and show the new one?.


Solution

  • For the "previous one also remains on the screen" problem: don't keep making a new annotation and calling addAnnotation if you don't want to keep adding new annotations. Instead, keep hold of the annotation that you add, and move it later using its coordinate property. Something like this maybe:

    class ViewController: UIViewController, MKMapViewDelegate {
    
        @IBOutlet weak var mapView: MKMapView!
    
        var annotationForThing: MKPointAnnotation?    
        var coordinateOfThing: CLLocationCoordinate2D? {
           didSet {
               guard let newCoord = coordinateOfThing else {
                   if let existing = annotationForThing {
                       mapView.removeAnnotation(existing)
                   }
                   return
               }
               if let existing = annotationForThing {
                    existing.coordinate = coordinateOfThing
               }
               else {
                   let newAnnotation = MKPointAnnotation()
                   newAnnotation = coordinateOfThing
                   mapView.addAnnotation(newAnnotation)
                   annotationForThing = newAnnotation
               }
           }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            mapView.delegate = self // or connect in storyboard
        }