I am currently getting some locations from a web request using alamofire, store them in my Object array and then display them on a MKMapView.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else {
return nil
}
let annotationIdentifier = "AnnotationIdentifier"
var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
}
else {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
if let annotationView = annotationView {
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "atm_map_icon")
}
return annotationView
}
And here is where i parse the json, put the result in an array and the loop through the array and add the markers to the map
for var i in 0..<json.count{
let name = json[i]["Name"].string
let address = json[i]["Address"].string
let lat = json[i]["Lat"].double
let lon = json[i]["Lon"].double
let atm = Atm(name: name!,address: address!,lat: lat!,lon: lon!)
self.atmArrayList.append(atm)
}
print(self.atmArrayList.count)
}
for atm in self.atmArrayList{
let atmPin = AtmAnnotation(title: atm.name!, subtitle: atm.address!, atm: atm, coordinate: CLLocationCoordinate2D(latitude: atm.lat!, longitude: atm.lon!))
self.annotationArray.append(atmPin)
}
self.atmMapView.addAnnotations(self.annotationArray)
What i want to achieve is so when the user clicks on the rightCalloutAccessoryView button, i want to pass the specific Atm object of that Annotation to the another ViewController.
My guess is to give the Annotations an id and then get the Atm from the Atm array in that specific position??
You need to implement this method of MapViewDelegate in your viewController
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let anotherViewController = self.storyboard?.instantiateViewController(withIdentifier: "anotherViewController") as! AnotherViewController
if let atmPin = view.annotation as? AtmAnnotation
{
anotherViewController.currentAtmPin = atmPin
}
self.navigationController?.pushViewController(anotherViewController, animated: true)
}
Hope this helps
Related
I'm trying to code an app that displays different images on a AppleMap. I managed to set one image pin but I don't know how to set different images.
In my view didLoad I wrote :
self.pin = AnnotationPin(title: sport, subtitle: "ouiii", coordinate: coordinate)
self.MyMapView.addAnnotation(self.pin)
In the viewcontroller I have:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else {
return nil
}
let annotationIdentifier = "AnnotationIdentifier"
var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
}
else {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
if let annotationView = annotationView {
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "kite")
}
return annotationView
}
I made another swift file called annotation which contains:
class AnnotationPin: NSObject, MKAnnotation {
let coordinate: CLLocationCoordinate2D
let title: String?
let subtitle: String?
init(title:String, subtitle: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
super.init()
}}
I already called this class for subtitles and titles and I suppose I can call it again to choose my Image. But I don't know how to do it, and I don't find answers on other topics.
You can add an image property to your AnnotationPin class and then in viewForAnnotation you use a conditional downcast to see if you are dealing with one of your annotations. If you are then you can use the image property
class AnnotationPin: NSObject, MKAnnotation {
let coordinate: CLLocationCoordinate2D
let title: String?
let subtitle: String?
let image: UIImage?
init(title:String, subtitle: String, image: UIImage, coordinate: CLLocationCoordinate2D) {
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
self.image = image
super.init()
}}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let myAnnotation = annotation as? AnnotationPin else {
return nil
}
let annotationIdentifier = "AnnotationIdentifier"
var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
}
else {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
if let annotationView = annotationView {
annotationView.canShowCallout = true
annotationView.image = myAnnotation.image
}
return annotationView
}
I am showing 3 distinct annotations in a map. To achive this I have a enum as a class variable which indicates the current value of the image name to be set in the MKAnnotationView property. I have subclassed MKAnnotationView to sore a class variable to get the image name in case of annotation reuse.
The problem is that when I drag the map leaving the annotations out of view and when I drag it again to see the annotations, these have their images exchanged.
My enum and custom MKAnnotationView class:
enum AnnotationIcon: String {
case taxi
case takingIcon
case destinyIcon
}
final class MyMKAnnotationView: MKAnnotationView {
var iconType: String = ""
}
And this is my viewFor annotation function:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else {
return nil
}
let identifier = "Custom annotation"
var annotationView: MyMKAnnotationView?
guard let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MyMKAnnotationView else {
let av = MyMKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView = av
annotationView?.annotation = annotation
annotationView?.canShowCallout = true
annotationView?.translatesAutoresizingMaskIntoConstraints = false
annotationView?.widthAnchor.constraint(equalToConstant: 35).isActive = true
annotationView?.heightAnchor.constraint(equalToConstant: 35).isActive = true
annotationView?.iconType = annotationIcon.rawValue //AnnotationIcon enum class variable
annotationView?.image = UIImage(named: annotationView?.iconType ?? "")
return av
}
annotationView = dequeuedAnnotationView
annotationView?.image = UIImage(named: annotationView?.iconType ?? "")
return annotationView
}
Images that explain the problem:
Before the draggin:
After the draggin:
What is the way for each annotation to retrieve the correct image in case of reuse?
Thank you.
Before reusing the MyMKAnnotationView you've to empty the already set image in the prepareForReuse method.
final class MyMKAnnotationView: MKAnnotationView {
var iconType: String = ""
//...
override func prepareForReuse() {
super.prepareForReuse()
image = nil // or set a default placeholder image instead
}
}
Update: As suspected the iconType is not getting set before you're trying to set the image of MyMKAnnotationView. Either you need to set the iconType before setting the image, like this:
annotationView?.iconType = AnnotationIcon.taxi.rawValue
annotationView?.image = UIImage(named: annotationView?.iconType ?? "")
You can improve this a lot by being the image returning logic to the AnnotationIcon.
enum AnnotationIcon: String {
//...
var annotationImage: UIImage? { UIImage(named: rawValue) }
}
Then change the MyMKAnnotationView as follows:
final class MyMKAnnotationView: MKAnnotationView {
var iconType = AnnotationIcon.taxi {
didSet {
image = iconType.annotationImage // image is set whenever `iconType` is set
}
}
//...
}
Then in viewForAnnotation:
var iconTypes = [AnnotationIcon]() // should be equal to the number of annotation
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
//...
dequeuedAnnotationView.annotation = annotation
dequeuedAnnotationView.iconType = iconType
}
Your problem is that you only set the iconType property when you create the annotation view. When an annotation view is reused, you set the image based on that property rather the current annotation.
Really, there is no need for the iconType property. You should just always use an icon value from your annotation. The annotation is the data model.
You also don't set the view's annotation property correctly in the case of reuse.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let myAnnotation = annotation as? MyAnnotation else {
return nil
}
let identifier = "Custom annotation"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MyMKAnnotationView
if annotationView == nil {
annotationView = MyMKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.canShowCallout = true
annotationView?.translatesAutoresizingMaskIntoConstraints = false
annotationView?.widthAnchor.constraint(equalToConstant: 35).isActive = true
annotationView?.heightAnchor.constraint(equalToConstant: 35).isActive = true
}
annotationView?.annotation = MyAnnotation
annotationView?.image = UIImage(named: MyAnnotation.icon.rawValue)
return annotationView
}
I have solved this issue subclassing the MKPointAnnotation to know what type of Annotation I am reusing:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else {
return nil
}
var annotationView: MKAnnotationView?
switch annotation {
case is MyCustomTaxiAnnotation:
annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationTaxiID, for: annotation)
case is MyCustomOriginAnnotation:
annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationOriginID, for: annotation)
case is MyCustomDestinyAnnotation:
annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationDestinyID, for: annotation)
default:
annotationView = nil
}
if annotationView == nil {
switch annotationIcon {
case .destinyIcon:
annotationView = MyDestinyView(annotation: annotation, reuseIdentifier: annotationDestinyID)
annotationView?.annotation = MyCustomDestinyAnnotation()
case .takingIcon:
annotationView = MyOriginView(annotation: annotation, reuseIdentifier: annotationOriginID)
annotationView?.annotation = MyCustomOriginAnnotation()
case .taxi:
annotationView = MyTaxiView(annotation: annotation, reuseIdentifier: annotationTaxiID)
annotationView?.annotation = MyCustomTaxiAnnotation()
}
} else {
annotationView?.annotation = annotation
}
return annotationView
}
For example, the Taxi annotation is a subclass of MKPointAnnotation:
let annotation = MyCustomTaxiAnnotation()
final class MyCustomTaxiAnnotation: MKPointAnnotation {
///...
}
So, taking in account that, I am able to reuse a custom annotation view properly. I have also register the custom MKAnnotationView:
map.register(MyOriginView.self, forAnnotationViewWithReuseIdentifier: annotationOriginID)
map.register(MyDestinyView.self, forAnnotationViewWithReuseIdentifier: annotationDestinyID)
map.register(MyTaxiView.self, forAnnotationViewWithReuseIdentifier: annotationTaxiID)
I am new to coding and Stack Overflow, so forgive me if I do something wrong.
I am using MKLocalSearch to display locations specified by a string. I have a user and location, so everything is setup.
I have added MKLocalSearch to my app, and it works correctly but now puts an MKPointAnnotation over the users' location. Of course, I want the famous blue dot to appear rather than an annotation.
I have already tried going over the code and to look up this issue but haven't had any luck finding a solution.
Here is my MKLocalSearch Code:
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = "Dispensaries"
request.region = MapView.region
let search = MKLocalSearch(request: request)
search.start(completionHandler: {(response, error) in
if error != nil {
print("Error occured in search")
} else if response!.mapItems.count == 0 {
print("No matches found")
} else {
print("Matches found")
for item in response!.mapItems {
let annotation = MKPointAnnotation()
annotation.title = item.name
annotation.coordinate = item.placemark.coordinate
DispatchQueue.main.async {
self.MapView.addAnnotation(annotation)
}
print("Name = \(String(describing: item.name))")
print("Phone = \(String(describing: item.phoneNumber))")
print("Website = \(String(describing: item.url))")
}
}
})
Here is my viewForAnnotation
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var view = mapView.dequeueReusableAnnotationView(withIdentifier: "reuseIdentifier") as? MKMarkerAnnotationView
if view == nil {
view = MKMarkerAnnotationView(annotation: nil, reuseIdentifier: "reuseIdentifier")`
let identifier = "hold"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView == nil {
annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.canShowCallout = true
let btn = UIButton(type: .detailDisclosure)
annotationView?.rightCalloutAccessoryView = btn
} else {
annotationView?.annotation = annotation
}
}
view?.annotation = annotation
view?.displayPriority = .required
return view
}
}
In func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) check the annotation type e.g.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation { return nil }
// the rest of your code
}
If you return nil from this method, the MKMapView uses its default built in annotation views, for MKPointAnnotation it uses the red pin, for MKUserLocation the blue dot you are looking for.
Is there a way to parse an array of information to the next VC when the users tap the rightCalloutAccessoryView?
Lets say I have this set of information that I need to parse over:
[name: "XXX",gender: "YYY",lat: 11.1111,lon: 22.2222]
and in the next VC we will display these info in a 'profile page' manner. My implementation thus far is as such:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseIdentifier = "pin"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
annotationView?.canShowCallout = true
annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
} else {
annotationView?.annotation = annotation
}
annotationView?.image = UIImage(named: "PersonIcon")
return annotationView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
viewActivity()
}
}
func viewActivity() {
let controller = storyboard?.instantiateViewController(withIdentifier: "ActivityView") as! ActivityViewController
controller.parsedInfo = /*parsedInfo*/
navigationController?.pushViewController(controller, animated: true)
}
EDIT:
Code for addAnnotation in viewDidLoad:
FIRHelperClient.sharedInstance.getLocationsForActivities(ref) { (results, error) in
if let error = error {
print(error.localizedDescription)
} else {
for result in results! {
guard let lat = result.lat, let lon = result.lon, let activity = result.searchActivities else {
print("locationForActivities did not return lat or lon")
return
}
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
annotation.title = activity
self.mapView.addAnnotation(annotation)
}
}
}
var lat:CLLocationDegrees = 40.748708
var long:CLLocationDegrees = -73.985643
var latDelta:CLLocationDegrees = 0.01
var longDelta:CLLocationDegrees = 0.01
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, long)
var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
mapView.setRegion(region, animated: true)
var information = MKPointAnnotation()
information.coordinate = location
information.title = "Test Title!"
information.subtitle = "Subtitle"
mapView.addAnnotation(information)
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if !(annotation is MKPointAnnotation) {
return nil
}
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView?.image = UIImage(named:"annotation")
anView?.canShowCallout = true
}
else {
anView?.annotation = annotation
}
return anView
}
I need to load custom image for the annotation in Mapview. I have an image named "Annotation" and I am trying to call it in viewfor annotation method. How can I achieve this?
Here is the answer:
Swift 4:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// Don't want to show a custom image if the annotation is the user's location.
guard !(annotation is MKUserLocation) else {
return nil
}
// Better to make this class property
let annotationIdentifier = "AnnotationIdentifier"
var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
}
else {
let av = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
av.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
annotationView = av
}
if let annotationView = annotationView {
// Configure your annotation view here
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "yourImage")
}
return annotationView
}
Swift 3:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// Don't want to show a custom image if the annotation is the user's location.
guard !(annotation is MKUserLocation) else {
return nil
}
// Better to make this class property
let annotationIdentifier = "AnnotationIdentifier"
var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
}
else {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
if let annotationView = annotationView {
// Configure your annotation view here
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "yourImage")
}
return annotationView
}
Swift 2.2:
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
// Don't want to show a custom image if the annotation is the user's location.
guard !annotation.isKindOfClass(MKUserLocation) else {
return nil
}
let annotationIdentifier = "AnnotationIdentifier"
var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationIdentifier) {
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
}
else {
let av = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
av.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure)
annotationView = av
}
if let annotationView = annotationView {
// Configure your annotation view here
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "yourImage")
}
return annotationView
}
Swift 4.0
var coordinates: [[Double]]!
var addresses:[String]!
In viewDidload() add following code to add annotations to MapvView.
coordinates = [[28.4344,72.5401],[28.85196,72.3944],[28.15376,72.1953]]// Latitude,Longitude
addresses = ["Address1","Address2","Address3"]
self.mapView.delegate = self // set MapView delegate to self
for i in 0...2 {
let coordinate = coordinates[i]
let point = CustomAnnotation(coordinate: CLLocationCoordinate2D(latitude: coordinate[0] , longitude: coordinate[1] )) // CustomAnnotation is class and pass the required param
point.address = addresses[i] // passing only address to pin, you can add multiple properties according to need
self.mapView.addAnnotation(point)
}
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 28.856614, longitude: 72.3522219), span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
self.mapView.setRegion(region, animated: true)
Add new class having name CustomAnnotation inherited from MKAnnotation for our custom annotation
import MapKit
class CustomAnnotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var address: String!
init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
}
}
Add one more class having name AnnotationView inherited from MKAnnotationView. I am showing custom callout so it it is required to to override the overridefuncpoint() method to receive touch in custom callout view.
import MapKit
class AnnotationView: MKAnnotationView
{
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hitView = super.hitTest(point, with: event)
if (hitView != nil)
{
self.superview?.bringSubview(toFront: self)
}
return hitView
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let rect = self.bounds;
var isInside: Bool = rect.contains(point);
if(!isInside)
{
for view in self.subviews
{
isInside = view.frame.contains(point);
if isInside
{
break;
}
}
}
return isInside;
}
}
Now implement viewForannotation MapView delegate as follow
extension YourViewC: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation
{
return nil
}
var annotationView = self.mapView.dequeueReusableAnnotationView(withIdentifier: "CustomPin")
if annotationView == nil{
annotationView = AnnotationView(annotation: annotation, reuseIdentifier: "CustomPin")
annotationView?.canShowCallout = false
}else{
annotationView?.annotation = annotation
}
annotationView?.image = UIImage(named: "bluecircle") // Pass name of your custom image
return annotationView
}
func mapView(_ mapView: MKMapView,
didSelect view: MKAnnotationView){
let annotation = view.annotation as? CustomAnnotation
print(annotation?.address) // get info you passed on pin
// write code here to add custom view on tapped annotion
}
The best way to achieve this is using custom class to store annotations.
import UIKit
import MapKit
import CoreLocation
class Annotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D = CLLocationCoordinate2D()
var title: String?
var subtitle: String?
var strTitle = ""
var strImgUrl = ""
var strDescr = ""
init(coordinates location: CLLocationCoordinate2D, title1: String, description: String, imgURL: String) {
super.init()
coordinate = location
title = title1
subtitle = description
strTitle = title1
strImgUrl = imgURL
strDescr = description
}
}
Now use this class to store annotation and populate your pins.
// MapViewController.swift
let myAnnotation1: Annotation = Annotation.init(coordinates: CLLocationCoordinate2D.init(latitude: 30.733051, longitude: 76.763042), title1: "The Mayflower Renaissance Hotel", description: "The Histroic hotel has been the site of saveral dramatic locations.", imgURL: "custom.jpg")
self.uvMApView.addAnnotation(myAnnotation1)
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if (annotation is MKUserLocation) {
return nil
}
// try to dequeue an existing pin view first
let AnnotationIdentifier = "AnnotationIdentifier"
let myAnnotation1 = (annotation as! Annotation)
let pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: AnnotationIdentifier)
pinView.canShowCallout = true
pinView.image = UIImage(named: myAnnotation1. strImgUrl)!
return pinView
}
After spending lot of time, i came up with a simple code.
1. Don't use .pdf images, use only .png images with three different sizes such as 1x, 2x, 3x. Below is my sample code.
#IBOutlet var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
mapViewSetup()
}
func mapViewSetup(){
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
mapView.delegate = self
mapView.mapType = .standard
mapView.isZoomEnabled = true
mapView.isScrollEnabled = true
mapView.showsUserLocation = false
if let coor = mapView.userLocation.location?.coordinate{
mapView.setCenter(coor, animated: true)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
mapView.mapType = MKMapType.standard
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let region = MKCoordinateRegion(center: locValue, span: span)
mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = locValue
annotation.title = "Arshad"
annotation.subtitle = "BrightSword Technologies Pvt Ltd"
mapView.addAnnotation(annotation)
self.locationManager.stopUpdatingLocation()
//centerMap(locValue)
}
private func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error.localizedDescription)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "customannotation")
annotationView.image = UIImage(named: "icon_location_pin")
annotationView.canShowCallout = true
return annotationView
}
Hope it will help someone.
You can also do like this:
let reuseId = "pin"
var your_pin = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
let your_image = UIImage (named: "your_image")
pinView?.image = your_image
pinView?.canShowCallout = true
I think it is the more easily answer.