How add description to MKPolyline & MKPolygon? - swift

How add annotations to polyline and polygon in Swift & MapKit? By Point is simple.

S.,
I'm not sure what you're asking here, but I assume you want to display an annotation somewhere on the polyline.
First the intro how to get the the polyline:
So, lets assume you have an array of CLLocation objects that will draw the polyline on the map. We call this array of location objects: myLocations and it's of type [CLLocation]. Now somewhere in your app you call a method that creates the polyline, we call this method createOverlayObject(locations: [CLLocation]) -> MKPolyline.
Your call could look like this:
let overlayPolyline = createOverlayObject(myLocations)
The method you called then could look like this:
func createOverlayObject(locations: [CLLocation]) -> MKPolyline {
//This method creates the polyline overlay that you want to draw.
var mapCoordinates = [CLLocationCoordinate2D]()
for overlayLocation in locations {
mapCoordinates.append(overlayLocation.coordinate)
}
let polyline = MKPolyline(coordinates: &mapCoordinates[0], count: mapCoordinates.count)
return polyline
}
This was the first part, don't forget to implement the mapView(_: rendererForOverlay overlay:) to get the line rendered. this part could look something like this:
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
//This function creatss the renderer for the polyline overlay. This makes the polyline actually display on screen.
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = mapLineColor //The color you want your polyline to be.
renderer.lineWidth = self.lineWidth
return renderer
}
Now the second part get the annotation somewhere on the map. This is actually straight forward if you know what the coordinates are where you want to put your annotation. creating and displaying the annotation is straightforward again, assuming you have defined a map view called myNiceMapView:
func createAnnotation(myCoordinate: CLLocationCoordinate2D) {
let myAnnotation = MKPointAnnotation()
myAnnotation.title = "My nice title"
startAnnotation.coordinate = myCoordinate
self.myNiceMapView.addAnnotations([myAnnotation])
}
Don't forget to implement mapView(_: MKMapView, viewForAnnotation annotation:) -> MKAnnotationView? method, which might look like:
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
//This is the mapview delegate method that adjusts the annotation views.
if annotation.isKindOfClass(MKUserLocation) {
//We don't do anything with the user location, so ignore an annotation that has to do with the user location.
return nil
}
let identifier = "customPin"
let trackAnnotation = MKAnnotationView.init(annotation: annotation, reuseIdentifier: identifier)
trackAnnotation.canShowCallout = true
if annotation.title! == "Some specific title" { //Display a different image
trackAnnotation.image = UIImage(named: "StartAnnotation")
let offsetHeight = (trackAnnotation.image?.size.height)! / 2.0
trackAnnotation.centerOffset = CGPointMake(0, -offsetHeight)
} else { //Display a standard image.
trackAnnotation.image = UIImage(named: "StopAnnotation")
let offsetHeight = (trackAnnotation.image?.size.height)! / 2.0
trackAnnotation.centerOffset = CGPointMake(0, -offsetHeight)
}
return trackAnnotation
}
Now the challenges is finding the right coordinate where to put your annotation. I can't find anything better than that you have a CLLocationCoordinate2D that references the location you want to put the annotation. Then with a for-in loop find the location where you want to put your annotation, something like this:
for location in myLocations {
if (location.latitude == myReferenceCoordinate.latitude) && (location.longitude == myReferenceCoordinate.longitude) {
self.createAnnotation(location: CLLOcationCoordinate2D)
}
}
Hope this answers your question.

Related

Prevent replacing of WMS Overlay while adding Polygon or Polyline to MKMapView

I have implemented Web Map Service in the MKMapView by subclassing the MKTileOverlay & rendering it using MKTileOverlayRenderer. It works fine and displays the custom map properly.
When I call method like mapView.addOverlay(polyLine) to add Polyline or Polygon. The WMS overlay gets replaced with the Apple Maps overly.
// Set up the overlay and adds it to MKMapView.
func setupTileRenderer() {
let wmsURL = formTemplate?.wmsURL
let overlay = WMSTileOverlay(urlTemplate: wmsURL)
overlay.canReplaceMapContent = true
mapView.addOverlay(overlay, level: .aboveLabels)
tileRenderer = MKTileOverlayRenderer(tileOverlay: overlay)
wmsTileOverlay = overlay
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
let render = MKPolylineRenderer(overlay: overlay)
render.lineWidth = 2
render.strokeColor = UIColor.red
return render
} else if overlay is MKPolygon {
let render = MKPolygonRenderer(overlay: overlay)
render.lineWidth = 2
render.strokeColor = UIColor.red
return render
} else if overlay is WMSTileOverlay {
return tileRenderer!
}
return MKOverlayRenderer(overlay: overlay)
}
How do I prevent this? I don't want wmsTileOverlay to get replaced while adding polyline or polygon.
I realised that before drawing the polygon I was removing the previous overlays so at that time I was removing all the overlays. Just checking the overlay is WMSTileOverlay then not removing it.
/// Clears the overlays added by the user.
func clearOverlaysOnMapView() {
for overlay in mapView.overlays {
if !(overlay is WMSTileOverlay) {
mapView.removeOverlay(overlay)
}
}
}

annotation Display Priority doesn't do what I expect, how to keep custom pin on screen

I use the code below on view did load to add a custom annotation icon for the map center that the user started at so that if they scroll away they can always see their starting point.
if let lat = curBlip.blip_lat, let lon = curBlip.blip_lon {
let mapCenter = CLLocationCoordinate2DMake(lat, lon)
let mapSpan = MKCoordinateSpanMake(0.01, 0.01)
let mapRegion = MKCoordinateRegionMake(mapCenter, mapSpan)
self.map.setRegion(mapRegion, animated: true)
let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "Your Blips Location"
annotation.subtitle = "Subtitle Placeholder"
self.map.addAnnotation(annotation)
When the view loads I load that annotation so its always first and I set a bool named "set" to true after the first annotation to ensure that it gets the custom icon. The issue I am having is that even though I have the annotation set to display priority required the annotation disappears when I move the map away. How can I make that annotation always persist or is there a better way to set a "this is where the map started" circle that doesn't go away?
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if set {
return nil
} else {
let view = MKAnnotationView(annotation: annotation, reuseIdentifier: "annotationId")
view.image = UIImage(named: "locationArea50")
view.canShowCallout = true
view.displayPriority = .required
set = true
return view
}
Then after I scroll the map away a little bit, I suspect scrolling far enough that the system has to make them reappear the annotation disappears. I assume this has to do with how the grouping of annotations works but that blue annotation is special and I want it to always be present, which is what I thought displayPriority did.
The default value of displayPriority is .required .
So for correct overlapping you need to downgrade priority of red annotations:
redAnnotation.displayPriority = .defaultHigh

How to delay callout from showing when annotation selected in MKMapView? Swift 4

(This is my first stack overflow question haha)
UPDATE:
From this link - Center MKMapView BEFORE displaying callout
I implemented the solution from Thermometer, however selecting and deselecting the annotation makes it look like my application is glitching.
I think the best way would be to delay the callOut (detail pop up) from appearing by a few seconds so the map has time to move first.
Here is my code:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let annotation = view.annotation else {
return
}
let currentAnnotation = view.annotation as? MapMarker
Global.currentAnnotation = currentAnnotation
findRelatinoshipLines()
if Global.showLifeStoryLines {
var locations = lifeStoryAnnotations.map { $0.coordinate }
let polyline = MKPolyline(coordinates: &locations, count: locations.count)
Global.finalLineColor = Global.lifeStoryColor
mapView.addOverlay(polyline)
}
if Global.showFatherLines {
var fatherLocations = fatherTreeAnnotations.map { $0.coordinate }
let fatherPolyline = MKPolyline(coordinates: &fatherLocations, count: fatherLocations.count)
Global.finalLineColor = Global.fatherLineageColor
mapView.addOverlay(fatherPolyline)
}
if Global.showMotherLines {
var motherLocations = motherTreeAnnotations.map { $0.coordinate }
let motherPolyline = MKPolyline(coordinates: &motherLocations, count: motherLocations.count)
Global.finalLineColor = Global.motherLineageColor
mapView.addOverlay(motherPolyline)
}
if Global.showSpouseLines {
var locations = spouseAnnotations.map { $0.coordinate }
let polyline = MKPolyline(coordinates: &locations, count: locations.count)
Global.finalLineColor = Global.spouseColor
mapView.addOverlay(polyline)
}
if Global.zoomChange == true {
Global.zoomChange = false
} else {
let currentRegion = mapView.region
let span = currentRegion.span
let location = currentAnnotation!.coordinate
let region = MKCoordinateRegion(center: location, span: span)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
mapView.setCenter(annotation.coordinate, animated: true)
//mapView.setRegion(region, animated: true)
}
}
}
CONTINUED:
Basically I'm working on a family genealogy application that displays events from relatives on a map.
When I click an annotation (event) the details (who event belongs to, where and when, etc) pops up above with an information button to show the selected person.
I have it set up to set the MKMapView region so that the selected annotation is centered each time a new annotation is clicked.
The problem is when I click an event that is on the edge of the screen, my annotation title/description pops up off centered so that it fits on my screen because it doesn't know that I plan on re-centering the map view around said annotation.
I was wondering if there was any way to make the title/description appear centered directly above the selected annotation so that when I move the map everything is centered and fits on the screen.
Here are some screenshots of what I'm talking about:
Before and After
Solved it by calling setCenter with a slight delay in mapView(_:didSelect:):
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let annotation = view.annotation else {
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
mapView.setCenter(annotation.coordinate, animated: true)
}
}

Draw Polyline With Border Mapbox, iOS

I'm using Mapbox iOS SDK and trying to draw a polyline without geojson. I tried to get the route with this method:
func calculateRoute() {
...
let options = NavigationRouteOptions(waypoints: [origin, destination], profileIdentifier: .automobileAvoidingTraffic)
Directions.shared.calculate(options) { (waypoints, routes, error) in
guard let route = routes?.first else { return }
self.showPreview(route: route)
}
}
Then I tried to draw a route.
func showPreview(route: Route) {
guard let steps = route.legs.first?.steps else { return }
var points = [CLLocationCoordinate2D]()
for step in steps {
points.append(step.maneuverLocation)
}
let line = MGLPolyline(coordinates: &points, count: UInt(points.count))
mapView?.addAnnotation(line)
}
It draws a polyline on the map view. I could change the color and the width of the polyline with two delegate methods (MGLMapViewDelegate):
func mapView(_ mapView: MGLMapView, lineWidthForPolylineAnnotation annotation: MGLPolyline) -> CGFloat {
return 10
}
func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> UIColor {
return .blue
}
but I can't find a method to set a border width and border color around the polyline. Is there any way to do that?
It looks like I had a similar use case to you (i.e. not using geojson) and ended up with something like this. By associating your route with an MGLLineStyleLayer you can control the visual parameters of the line.
func showPreview(route: Route) {
guard route.coordinateCount > 0 else { return }
// Convert the route’s coordinates into a polyline
var routeCoordinates = route.coordinates!
let polyline = MGLPolylineFeature(coordinates: &routeCoordinates, count: route.coordinateCount)
// If there's already a route line on the map, reset its shape to the new route
if let source = mapView.style?.source(withIdentifier: "route-source") as? MGLShapeSource {
source.shape = polyline
} else {
let source = MGLShapeSource(identifier: "route-source", features: [polyline], options: nil)
// Customize the route line color and width
let lineStyle = MGLLineStyleLayer(identifier: "route-style", source: source)
lineStyle.lineColor = NSExpression(forConstantValue: UIColor.blue)
lineStyle.lineWidth = NSExpression(forConstantValue: 3)
// Add the source and style layer of the route line to the map
mapView.style?.addSource(source)
mapView.style?.addLayer(lineStyle)
}
}
You want to add a border and control how that looks. If you take a look at this example on the Mapbox website: Line style Example they do what you want by creating a second MGLLineStyleLayer and inserting it below the first one. They call the second layer casingLayer. This is their code so you can see it is formed the same way as the first layer.
let casingLayer = MGLLineStyleLayer(identifier: "polyline-case", source: source)
// Add your formatting attributes here. See example on website.
Then they insert it below the first line and because it has a wider width, shows as a border.
style.insertLayer(casingLayer, below: lineStyle)
Hope this helps.

MKPolygon Swift not appearing

Im trying to create a shape on my map but I'm having a hard time finding any information about mkpolygon with swift. I was hoping someone on here would see this and point me into the right direction.
This is what I currently have but the polygon is not appearing.
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
let pr = MKPolygonRenderer(overlay: overlay)
pr.strokeColor = UIColor.purpleColor()
pr.lineWidth = 14
return pr
}
func createPolyline(mapView: MKMapView) {
var points=[CLLocationCoordinate2DMake(49.142677, -123.135139),CLLocationCoordinate2DMake(49.142730, -123.125794),CLLocationCoordinate2DMake(49.140874, -123.125805),CLLocationCoordinate2DMake(49.140885, -123.135214)]
let polygon = MKPolygon(coordinates: &points, count: points.count)
self.mapView.addOverlay(polygon)
}
Turns out what I was forgetting was to set the map view delegate. I will leave this up incase anyone wants to see what I used to get mkpolygon working in swift.