听起来您想使用地标和注释。当您创建 MapView 时,请确保它符合 MKMapViewDelegate:
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
// once annotationView is added to the map, get the last one added unless it is the user's location:
if let annotationView = views.last {
// show callout programmatically:
mapView.selectAnnotation(annotationView.annotation!, animated: false)
// zoom to all annotations on the map:
mapView.showAnnotations(mapView.annotations, animated: true)
}
}
}
然后你可以从一个字符串中定位一个地址(这将是这样写的地址:123 Fake St., New York, NY ....
func createGeoLocationFromAddress(_ address: String, mapView: MKMapView) {
let completion:CLGeocodeCompletionHandler = {(placemarks: [CLPlacemark]?, error: Error?) in
if let placemarks = placemarks {
for placemark in placemarks {
mapView.removeAnnotations(mapView.annotations)
// Instantiate annotation
let annotation = MKPointAnnotation()
// Annotation coordinate
annotation.coordinate = (placemark.location?.coordinate)!
annotation.title = placemark.thoroughfare! + ", " + placemark.subThoroughfare!
annotation.subtitle = placemark.subLocality
mapView.addAnnotation(annotation)
mapView.showsPointsOfInterest = true
self.centerMapOnLocation(placemark.location!, mapView: mapView)
}
} else {
}
}
CLGeocoder().geocodeAddressString(address, completionHandler: completion)
}
func centerMapOnLocation(_ location: CLLocation, mapView: MKMapView) {
let regionRadius: CLLocationDistance = 1000
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
然后你可以通过调用在地图上放置注释
createGeoLocationFromAddress(addressString, mapView: mapKit)
这应该可行。希望对你有帮助