How to enable MapKit floor level? - swift

I am trying to show floor level into my apple app. I know in apple map there are some selected place like airport or shopping mall where this floor level can be seen. I need to achieve exactly that. Just need to show the floor level where this is available. As you can see in the picture, in the right hand side of the image there are 5F,4F,3F,2F etc. I have searched the net but left with no clue yet.

You need to use MKOverlay. You would add each floor as an overlay to your MKMapView and show whatever floor the user selects, hide the others.
Here is a sample for making an overlay:
import MapKit
class MapOverlay: NSObject, MKOverlay {
var coordinate: CLLocationCoordinate2D
var boundingMapRect: MKMapRect
override init() {
let location = CLLocationCoordinate2D(latitude: 75.3307, longitude: -152.1929) // change these for the position of your overlay
let mapSize = MKMapSize(width: 240000000, height: 200000000) // change these numbers for the width and height of your image
boundingMapRect = MKMapRect(origin: MKMapPoint(location), size: mapSize)
coordinate = location
super.init()
}
}
class MapOverlayRenderer: MKOverlayRenderer {
let overlayImage: UIImage
init(overlay: MKOverlay, image: UIImage) {
self.overlayImage = image
super.init(overlay: overlay)
}
override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
guard let imageReference = overlayImage.cgImage else { return }
let rect = self.rect(for: overlay.boundingMapRect)
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0.0, y: -rect.size.height)
context.draw(imageReference, in: rect)
}
}
Then add it to your map:
let mapOverlay = MapOverlay()
mapView.addOverlay(mapOverlay)
And don't forget the delegate:
mapView.delegate = self
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
return MapOverlayRenderer(overlay: overlay, image: UIImage(named: "overlayImage")!)
}
}

Related

How to custom the image of MKAnnotation pin

I am trying to change the image that is inside the MKAnnotation without removing the rounded shape.
Here I create a custom class of MKAnnotation:
class MapPin: NSObject, MKAnnotation {
let title: String?
let locationName: String
let coordinate: CLLocationCoordinate2D
init(title: String, locationName: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.locationName = locationName
self.coordinate = coordinate
}
}
Here I create a MapPin and I add it to the mapView
func setPinUsingMKAnnotation() {
let pin1 = MapPin(title: "Here", locationName: "Device Location", coordinate: CLLocationCoordinate2D(latitude: 21.283921, longitude: -157.831661))
let coordinateRegion = MKCoordinateRegion(center: pin1.coordinate, latitudinalMeters: 800, longitudinalMeters: 800)
mapView.setRegion(coordinateRegion, animated: true)
mapView.addAnnotations([pin1])
}
The first image is what I created, the second image is what I would like it to be.
I even implemented MKMapViewDelegate:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var annotationView = MKAnnotationView()
annotationView.image = #imageLiteral(resourceName: "heart")
return annotationView
}
This is the result:
The rounded shape disappears.
I saw many tutorials about how to custom a pin, but they only explained how to put an image instead of the pin (like the hearth image above). I would like to know how to change the image (and color) of the pin and keep the rounded shape (see the blue pin image above).
Any hints? Thanks
If you want that rounded border, you can render it yourself, or easier, subclass MKMarkerAnnotationView rather than MKAnnotationView:
class CustomAnnotationView: MKMarkerAnnotationView {
override var annotation: MKAnnotation? {
didSet { configure(for: annotation) }
}
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
glyphImage = ...
markerTintColor = ...
configure(for: annotation)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(for annotation: MKAnnotation?) {
displayPriority = .required
// if doing clustering, also add
// clusteringIdentifier = ...
}
}
That way, not only do you get the circular border, but you get all of the marker annotation view behaviors (shows the title of the annotation view below the marker, if you select on the marker annotation view, it becomes larger, etc.). There’s a lot of marker annotation view behaviors that you probably don’t want to have to write from scratch if you don’t have to. By subclassing MKMarkerAnnotationView instead of the vanilla MKAnnotationView, you get all those behaviors for free.
For example, you could:
class CustomAnnotationView: MKMarkerAnnotationView {
static let glyphImage: UIImage = {
let rect = CGRect(origin: .zero, size: CGSize(width: 40, height: 40))
return UIGraphicsImageRenderer(bounds: rect).image { _ in
let radius: CGFloat = 11
let offset: CGFloat = 7
let insetY: CGFloat = 5
let center = CGPoint(x: rect.midX, y: rect.maxY - radius - insetY)
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: .pi, clockwise: true)
path.addQuadCurve(to: CGPoint(x: rect.midX, y: rect.minY + insetY), controlPoint: CGPoint(x: rect.midX - radius, y: center.y - offset))
path.addQuadCurve(to: CGPoint(x: rect.midX + radius, y: center.y), controlPoint: CGPoint(x: rect.midX + radius, y: center.y - offset))
path.close()
UIColor.white.setFill()
path.fill()
}
}()
override var annotation: MKAnnotation? {
didSet { configure(for: annotation) }
}
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
glyphImage = Self.glyphImage
markerTintColor = #colorLiteral(red: 0.005868499167, green: 0.5166643262, blue: 0.9889912009, alpha: 1)
configure(for: annotation)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(for annotation: MKAnnotation?) {
displayPriority = .required
// if doing clustering, also add
// clusteringIdentifier = ...
}
}
That yields:
Obviously, when you set glyphImage, set it to whatever image you want. The old SF Symbols doesn't have that “drop” image (though iOS 14 has drop.fill). But supply whatever 40 × 40 pt image view you want. I'm rendering it myself, but you can use whatever appropriately sized image from your asset catalog (or from the system symbols) that you want.
As an aside, since iOS 11, you wouldn't generally wouldn't implement mapView(_:viewFor:) at all, unless absolutely necessary (which it isn't in this case). For example, you can get rid of your viewFor method and just register your custom annotation view in viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
mapView.register(CustomAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
...
}

MapKit Overlays - Circles

I'm trying to add a circle overlay to the map but it never happens - the annotations are added but thats it
Here is the code sample
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer
let circle = MKCircleRenderer(overlay: overlay)
circle.fillColor = UIColor.black.withAlphaComponent(0.1)
circle.strokeColor = UIColor.red
circle.lineWidth = 9
return circle
}
let circle = MKCircle(center: coordinates, radius: 9000)
mapView.addAnnotation(Loka_Location)
mapView.addOverlay(circle)
You might have missed setting the delegate of the mapView.
mapView.delegate = self
and don't forget to
class ViewController: UIViewController, MKMapViewDelegate {}

How to draw custom shapes on MKMapView

I need to draw custom shapes like Arc, Semi-circle? I tried the below code but it's not rendering anything on the MKMapView.
Is this the right way to draw custom shapes?
class ViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
mapView.delegate = self
let center = CLLocationCoordinate2D(latitude: 15.463157486154865, longitude: 73.78846049308775)
let radius = CLLocationCoordinate2D(latitude: 15.495608080208948, longitude: 73.83418584279791)
addCircle(center: center, radius: radius)
}
private func createArcPath() -> UIBezierPath {
let center = CLLocationCoordinate2D(latitude: 15.463157486154865, longitude: 73.78846049308775)
// converting the coordinates to CGPoint with respect to MKMapView.
let centerPoint = mapView.convert(center, toPointTo: self.mapView)
// Creating bezierPath of arc.
let path = UIBezierPath(arcCenter: centerPoint, radius: 6080.205481929489, startAngle: CGFloat.pi, endAngle: CGFloat.pi * 2, clockwise: true)
return path
}
}
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKCircle {
let arcRenderer = MKOverlayPathRenderer()
arcRenderer.path = createArcPath().cgPath
arcRenderer.strokeColor = UIColor.red
arcRenderer.fillColor = UIColor.red
arcRenderer.lineWidth = 10
arcRenderer.alpha = 1
arcRenderer.lineCap = .round
return arcRenderer
}
return MKOverlayRenderer()
}
}
extension ViewController {
private func addCircle(center ccoordinate: CLLocationCoordinate2D, radius rcoordinate: CLLocationCoordinate2D) {
let centerLocation = CLLocation.init(latitude: ccoordinate.latitude, longitude: ccoordinate.longitude)
let radiusLocation = CLLocation.init(latitude: rcoordinate.latitude, longitude: rcoordinate.longitude)
let radius = centerLocation.distance(from: radiusLocation)
let circle = MKCircle(center: ccoordinate, radius: radius)
mapView.addOverlay(circle)
}
}
Use this to add custom shape in MAPVIEW
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer
{
if overlay is MKCircle
{
print("overlay latitude: "+String(overlay.coordinate.latitude))
print("overlay longitude: "+String(overlay.coordinate.longitude))
let circleOverlay = overlay as! MKCircle
if(circleOverlay.accessibilityPath != nil)
{
let arcRenderer = MKOverlayPathRenderer()
arcRenderer.path = circleOverlay.accessibilityPath?.cgPath
arcRenderer.strokeColor = UIColor.red
arcRenderer.lineWidth = 10
arcRenderer.alpha = 0.3
return arcRenderer
}
let circle = MKCircleRenderer(overlay: overlay)
circle.strokeColor = UIColor.black
circle.fillColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.1)
circle.lineWidth = 1
circle.alpha = 0.3
return circle
}
}
After some RND I came across a library curvyRoute & used it to draw arch on MKMapView.
// Adds arch overlay to the mapView
private func addArcOverlays() {
let pointA = CLLocationCoordinate2D(latitude: 15.463157486154865, longitude: 73.78846049308775)
let pointB = CLLocationCoordinate2D(latitude: 15.495608080208948, longitude: 73.83418584279791)
mapView.addOverlay(LineOverlay(origin: pointA, destination: pointB))
let style = LineOverlayStyle(strokeColor: .red, lineWidth: 4, alpha: 1)
let arc = ArcOverlay(origin: pointA, destination: pointB, style: style)
arc.radiusMultiplier = 0.5
mapView.addOverlay(arc)
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
switch overlay {
case let lineOverlay as LineOverlay:
let linerender = MapLineOverlayRenderer(lineOverlay)
setVisibleMapRect(linerender.overlay, animated: true)
return linerender
case let polyline as MKPolyline:
let renderer = MKPolylineRenderer(overlay: polyline)
renderer.strokeColor = UIColor.yellow.withAlphaComponent(0.5)
renderer.lineWidth = 4
return renderer
default:
return MKOverlayRenderer()
}
}

How to draw a constant line between a series of CLLocationCoordinate in a MapView

I have got an Array of CLLocationCoordinate. I want to draw a constant line.This line will link each adjacent CLLocationCoordinate so when the CLLocationCoordinates‘ distance is very near the line will look like a curve.I wonder how to develop it?
I tried to use the MKPolyLine like this:
var polyline:MKPolyline=MKPolyline(coordinates: arrcoordinate, count: arrcoordinate.count);
but it didn't meet my desire. I also tried like the MKGeodesicPolyline,and it also did not meet my desire.
I just make this probem simple,so I make an array of CLLocationCoordinate like this:
var arrcoordinate:[CLLocationCoordinate2D]=[CLLocationCoordinate2D].init();
arrcoordinate.append(CLLocationCoordinate2D.init(latitude: 100, longitude: 39));
arrcoordinate.append(CLLocationCoordinate2D.init(latitude: 128, longitude: 33));
arrcoordinate.append(CLLocationCoordinate2D.init(latitude: 118, longitude: 55));
arrcoordinate.append(CLLocationCoordinate2D.init(latitude: 122, longitude: 57));
print(arrcoordinate)
var polyline:MKPolyline=MKPolyline.init(coordinates: &arrcoordinate, count: arrcoordinate.count);
self.MapView.addOverlay(polyline);
and make the OverlayRender delegate like this:
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
var polylineRenderer=MKPolylineRenderer.init(overlay: overlay);
polylineRenderer.strokeColor = UIColor.white;
polylineRenderer.lineWidth=2
return polylineRenderer
}
return MKOverlayRenderer.init();
}
but there is no any line appears on the mapview,so I dont know why?
Works fine for me.
I had to change your code a little, because your coordinates are nonsensical. So my version of your code looks like this:
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var map: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.map.delegate = self
var arrcoordinate = [CLLocationCoordinate2D]()
arrcoordinate.append(CLLocationCoordinate2D(latitude: 0, longitude: 39))
arrcoordinate.append(CLLocationCoordinate2D(latitude: 28, longitude: 33))
arrcoordinate.append(CLLocationCoordinate2D(latitude: 18, longitude: 55))
arrcoordinate.append(CLLocationCoordinate2D(latitude: 22, longitude: 57))
let polyline = MKPolyline(coordinates: &arrcoordinate, count: arrcoordinate.count)
self.map.add(polyline)
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = .red
polylineRenderer.lineWidth = 2
return polylineRenderer
}
return MKOverlayRenderer()
}
}

Why my mapView does not display mi circle?

I have a mapView outlet in my iOS project and I added it to my code:
var overlay = MKCircle(center: coords, radius: 100)
self.mapView.add(overlay)
and also, to be sure, i added
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
print("aaa")
let circleRenderer = MKCircleRenderer(overlay: overlay)
circleRenderer.fillColor = UIColor.blue.withAlphaComponent(0.1)
circleRenderer.strokeColor = UIColor.blue
circleRenderer.lineWidth = 1
return circleRenderer
}
But my mapView is displayed but not the circle, why ?