如何使用Swift iOS在Mapview中添加两个注释?

Rak*_*han 2 mkmapview ios swift

 let latitude:CLLocationDegrees = 76.0100
 let longitude:CLLocationDegrees =25.3620


 let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)

 let latDelta:CLLocationDegrees = 1
 let lonDelta:CLLocationDegrees = 1
 let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)

 let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)

 mapView.setRegion(region, animated: true)

 let annotation:MKPointAnnotation = MKPointAnnotation()
    annotation.coordinate = location
    annotation.title = "Office ."
    annotation.subtitle = "My Office"

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {


    print("Locations = \(locations)")

    let userLocation: CLLocation = locations[0] as CLLocation

    //var latitude:CLLocationDegrees = userLocation.coordinate
    //var longitude:CLLocationDegrees = -121.934048
    //var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)

    let latDelta:CLLocationDegrees = 0.01
    let lonDelta:CLLocationDegrees = 0.01
    let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)

    let region:MKCoordinateRegion = MKCoordinateRegionMake(userLocation.coordinate, span)

    mapView.setRegion(region, animated: true)
Run Code Online (Sandbox Code Playgroud)

我为一个位置创建了一个注释。现在,我需要为另一个位置再创建一个注释,并将其显示在地图上。我该怎么证明?

Er.*_*hah 6

创建一个自定义类为“ MyAnnotation

import UIKit
import MapKit

class MyAnnotation: NSObject,MKAnnotation {

    var title : String?
var subTit : String?
var coordinate : CLLocationCoordinate2D

init(title:String,coordinate : CLLocationCoordinate2D,subtitle:String){

    self.title = title;
    self.coordinate = coordinate;
    self.subTit = subtitle;

}

}
Run Code Online (Sandbox Code Playgroud)

viewcontrollerviewdidload中添加以下代码:-

        let latitude:CLLocationDegrees = 76.0100
        let longitude:CLLocationDegrees = 25.3620

        let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)

        //Second Location lat and long
        let latitudeSec:CLLocationDegrees = 75.0100
        let longitudeSec:CLLocationDegrees = 24.3620

        let locationSec:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitudeSec, longitudeSec)

        let span:MKCoordinateSpan = MKCoordinateSpanMake(1, 1)

        let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)

        mapView.setRegion(region, animated: true)


        let myAn1 = MyAnnotation(title: "Office", coordinate: location, subtitle: "MyOffice");

        let myAn2 = MyAnnotation(title: "Office 1", coordinate: locationSec, subtitle: "MyOffice 1");

        mapView.addAnnotation(myAn1);
        mapView.addAnnotation(myAn2);
        //Instead of writing two lines of annotation we can use addAnnotations() to add.
Run Code Online (Sandbox Code Playgroud)

除此之外,您还可以使用for循环。

代码输出

希望这会帮助你。