I want to add a overlay path among multiple coordinates in mapview. I tried like below code, but it shows a error of "cannot invoke 'map' with an argument list of type ((CLLocation) -> CLLocationCoordinate2D)". Please let me know how can i fix this ?
My ViewController.swift file
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate{
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
//For Location 1
let location1 = CLLocationCoordinate2D(
latitude: 51.481188400000010000,
longitude: -0.190209099999947280
)
let annotation1 = MKPointAnnotation()
annotation1.coordinate = location1;
annotation1.title = "Chelsea"
annotation1.subtitle = "Chelsea"
let span = MKCoordinateSpanMake(0.15, 0.15)
let region1 = MKCoordinateRegion(center: location1, span: span)
mapView.setRegion(region1, animated: true)
mapView.addAnnotation(annotation1)
//For Location 2
let location2 = CLLocationCoordinate2D(
latitude: 51.554947700000010000,
longitude: -0.108558899999934510
)
let annotation2 = MKPointAnnotation()
annotation2.coordinate = location2;
annotation2.title = "Arsenal"
annotation2.subtitle = "Arsenal"
let region2 = MKCoordinateRegion(center: location1, span: span)
mapView.setRegion(region2, animated: true)
mapView.addAnnotation(annotation2)
var locations = [CLLocation(latitude: 51.481188400000010000, longitude: -0.190209099999947280), CLLocation(latitude: 51.554947700000010000,longitude: -0.108558899999934510)]
//This line shows error
var coordinates = locations.map({(location: CLLocation) -> CLLocationCoordinate2D in return location.coordinate})
var polyline = MKPolyline(coordinates: &coordinates, count: locations.count)
mapView.addOverlay(polyline)
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 5
return polylineRenderer
}
return nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This should work:
var coordinates = locations.map {
location in
return location.coordinate
}
One-liner:
var coordinates = locations.map { $0.coordinate }
The problem with your code was that locations is a variable of type [CLLocation!] (note the exclamation mark here), but you are declaring its elements as CLLocation (without the !) in the closure:
(location: CLLocation) -> CLLocationCoordinate2D
Related
I am struggling to try and Highlight the road between 2 points using MapKit. All I don't want directions i just want to try and Highlight the road between these two points.
My code is:
import UIKit
import MapKit
class ViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView!
struct Points {
var name: String
var lattitude: CLLocationDegrees
var longtitude: CLLocationDegrees
}
override func viewDidLoad() {
super.viewDidLoad()
let points = [
Points(name: "Point 1", lattitude: 52.100525, longtitude: -9.623071),
Points(name: "Point 2", lattitude: 52.07241, longtitude: -9.575299)
]
fetchPointsOnMap(points)
}
func fetchPointsOnMap(_ points: [Points]) {
for points in points {
let annotations = MKPointAnnotation()
annotations.title = points.name
annotations.coordinate = CLLocationCoordinate2D(latitude:
points.lattitude, longitude: points.longtitude)
mapView.addAnnotation(annotations)
}
}
}`
You can draw a line:
directionsRequest.transportType = MKDirectionsTransportType.automobile
//Draw polyline by using MKRoute so it follows the street roads...
for (k, item) in arrayarrayPlacemarks.enumerated() {
if k < (arrayarrayPlacemarks.count - 1) {
directionsRequest.source = item
directionsRequest.destination = arrayarrayPlacemarks[k+1]
let directions = MKDirections(request: directionsRequest)
directions.calculate { (response:MKDirections.Response!, error: Error!) -> Void in
if error == nil {
self.locRoute = response.routes[0] as? MKRoute
let geodesic:MKPolyline = self.locRoute!.polyline
self.mapView.addOverlay(geodesic)
}
}
}
}
Delegate:
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay.isKind(of: MKPolyline.self){
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.fillColor = UIColor.blue
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.lineWidth = 2
return polylineRenderer
}
return MKOverlayRenderer(overlay: overlay)
}
I want to give name to the green and right pin annotation above.
I see a video tutorial, and he can give name to the annotation by using annotation.title = but I don't know why I can get the name correctly show in my MapKit.
here is the code I use
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mapKit: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapKit.delegate = self
let bakrieTowerCoordinate = CLLocation(latitude: -6.23860724759536, longitude: 106.789429759178)
let GBKCoordinate = CLLocation(latitude: -6.23864960081552, longitude: 106.789627819772)
let locationGBK : CLLocationCoordinate2D = CLLocationCoordinate2DMake(-6.23864960081552, 106.789627819772)
let locationBakrieToweer : CLLocationCoordinate2D = CLLocationCoordinate2DMake(-6.23860724759536, 106.789429759178)
let annotation = MKPointAnnotation()
annotation.coordinate = locationGBK
annotation.title = "GBK"
annotation.subtitle = "Stadion"
mapKit.addAnnotation(annotation)
let annotation2 = MKPointAnnotation()
annotation2.coordinate = locationBakrieToweer
annotation2.title = "Bakrie Tower"
annotation2.subtitle = "Office"
mapKit.addAnnotation(annotation2)
zoomMapOn(location1: GBKCoordinate, location2: bakrieTowerCoordinate)
}
func zoomMapOn(location1: CLLocation, location2: CLLocation) {
let distanceOf2CoordinateInMeters = location1.distance(from: location2)
let radius = distanceOf2CoordinateInMeters * 3
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location1.coordinate, radius, radius)
mapKit.setRegion(coordinateRegion, animated: true)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
guard let locationName = annotation.title else {return nil}
if locationName == "GBK" {
annotationView.pinTintColor = UIColor.green
} else if locationName == "Bakrie Tower" {
annotationView.pinTintColor = UIColor.red
}
return annotationView
}
}
Add this code to your view controller -
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mapKit: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapKit.delegate = self
let bakrieTowerCoordinate = CLLocation(latitude: -6.23860724759536, longitude: 106.789429759178)
let GBKCoordinate = CLLocation(latitude: -6.23864960081552, longitude: 106.789627819772)
let locationGBK : CLLocationCoordinate2D = CLLocationCoordinate2DMake(-6.23864960081552, 106.789627819772)
let locationBakrieToweer : CLLocationCoordinate2D = CLLocationCoordinate2DMake(-6.23860724759536, 106.789429759178)
let annotation = MKPointAnnotation()
annotation.coordinate = locationGBK
annotation.title = "GBK"
annotation.subtitle = "Stadion"
mapKit.addAnnotation(annotation)
let annotation2 = MKPointAnnotation()
annotation2.coordinate = locationBakrieToweer
annotation2.title = "Bakrie Tower"
annotation2.subtitle = "Office"
mapKit.addAnnotation(annotation2)
zoomMapOn(location1: GBKCoordinate, location2: bakrieTowerCoordinate)
}
func zoomMapOn(location1: CLLocation, location2: CLLocation) {
let distanceOf2CoordinateInMeters = location1.distance(from: location2)
let radius = distanceOf2CoordinateInMeters * 3
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location1.coordinate, radius, radius)
mapKit.setRegion(coordinateRegion, animated: true)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
guard let locationName = annotation.title else {return nil}
if locationName == "GBK" {
annotationView.canShowCallout = true
} else if locationName == "Bakrie Tower" {
annotationView.pinTintColor = UIColor.red
}
annotationView.canShowCallout = true // Add this line in your code
return annotationView
}
}
When you tap on the pin, it will show the text, Like -
Just Add
annotationView.canShowCallout = true inside your mapView(_ mapView:). Thank you.
You need to set this property in mapView(_:viewFor:) before returning your annotationView:
annotationView.canShowCallout = true
Now when you tap the pin, it will show your text.
I am trying to make an app that tracks a user's location and creates a line following where the user went. I have created a bunch of annotations following where the user went, but can't figure out how to create a line between them. I am new to swift and Xcode and I have looked all over the internet but can't find anything that works. Picture of app with annotations following user location
Here is my code:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet var mapView: MKMapView?
//Map
#IBOutlet weak var map: MKMapView!
#IBOutlet weak var lblSpeed: UILabel!
let manager = CLLocationManager()
#IBOutlet weak var lblAltitude: UILabel!
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
lblAltitude.text = String(format:"%.2f", location.altitude)
lblSpeed.text = String(format:"%.2f", location.speed)
self.map.showsUserLocation = true
var testLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
var annotation = MKPointAnnotation()
annotation.coordinate = testLocation
map.addAnnotation(annotation)
var locationTest = [CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)]
var coordinates = locations.map({(location: CLLocation!) -> CLLocationCoordinate2D in return location.coordinate})
var polyline = MKPolyline(coordinates: &testLocation, count: locations.count)
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.lineWidth = 5
return polylineRenderer
}
return nil
}
}
You can try
let blueLocation1 = CLLocationCoordinate2D(latitude: lat1, longitude: lon1)
let blueLocation2 = CLLocationCoordinate2D(latitude: lat2, longitude: lon2)
let routeLine = MKPolyline(coordinates:[blueLocation1,blueLocation2], count:2)
self.mapView.add(routeLine)
// Also you may be keen to zoom out to show all annotations + seeing drawn line
func zoomToFitMapAnnotations(aMapView:MKMapView)
{
if(aMapView.annotations.count == 0)
{
return
}
var topLeftCoord = CLLocationCoordinate2D.init(latitude: -90, longitude: 180)
var bottomRightCoord = CLLocationCoordinate2D.init(latitude: 90, longitude: -180)
for i in 0..<aMapView.annotations.count
{
let annotation = aMapView.annotations[i]
topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
}
let resd = CLLocationCoordinate2D.init(latitude: topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5, longitude: topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5)
let span = MKCoordinateSpan.init(latitudeDelta: fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.3, longitudeDelta: fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.3)
var region = MKCoordinateRegion.init(center: resd, span: span);
region = aMapView.regionThatFits(region)
aMapView.setRegion(region, animated: true)
}
// Also rendererForOverlay func must be in class level not inside another func
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.lineWidth = 5
return polylineRenderer
}
return nil
}
For the practice of MapKit in iOS using Swift 2.0 targeted version iOS 8.0 drawing path between two points I am getting errors in my code that you can see above.
Here is my practice code:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet var map: MKMapView!
var geocoder:CLGeocoder = CLGeocoder()
var location:CLLocation = CLLocation(latitude: 38, longitude: -77)
var next:CLLocation = CLLocation(latitude: 38.21, longitude: -77.21)
var locMark:MKPlacemark?
var destMark:MKPlacemark?
var manager:CLLocationManager = CLLocationManager()
var source:MKMapItem?
var destination:MKMapItem?
var request:MKDirectionsRequest = MKDirectionsRequest()
var directions:MKDirections = MKDirections()
var directionsResponse:MKDirectionsResponse = MKDirectionsResponse()
var route:MKRoute = MKRoute()
override func viewDidLoad() {
super.viewDidLoad()
manager.requestAlwaysAuthorization()
map.mapType = MKMapType.Satellite
locMark = MKPlacemark(coordinate: CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude), addressDictionary: nil)
destMark = MKPlacemark(coordinate: CLLocationCoordinate2DMake(next.coordinate.latitude, next.coordinate.longitude), addressDictionary: nil)
source = MKMapItem(placemark: locMark)
destination = MKMapItem(placemark: destMark)
request.setSource(source)
request.setDestination(destination)
request.transportType = MKDirectionsTransportType.Automobile
request.requestsAlternateRoutes = true
directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler { (response:MKDirectionsResponse?, error:NSError?) -> Void in
if error == nil {
self.directionsResponse = response!
self.route = self.directionsResponse.routes[0] as! MKRoute
map.addOverlay(route.polyline, level: MKOverlayLevel.AboveRoads)
} else {
println(error)
}
}
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
println("redenrerForOverlay")
if(overlay.isKindOfClass(MKPolyline)) {
var renderer: MKPolylineRenderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = Colors.psnGreen
renderer.lineWidth = 5
return renderer
}
return nil
}
func mapView(mapView: MKMapView!, viewForOverlay overlay: MKOverlay!) -> MKOverlayView! {
println("ViewForOverlay")
if (overlay.isKindOfClass(MKPolyline)) {
var lineView: MKPolylineView = MKPolylineView(overlay: overlay)
lineView.backgroundColor = Colors.psnGreen
return lineView;
}
return nil;
}
}
Zeeshan you just need to delete those two lines and add the two lines from Mark Answer , this below code is working fine:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet var map: MKMapView!
var geocoder:CLGeocoder = CLGeocoder()
var location:CLLocation = CLLocation(latitude: 38, longitude: -77)
var next:CLLocation = CLLocation(latitude: 38.21, longitude: -77.21)
var locMark:MKPlacemark?
var destMark:MKPlacemark?
var manager:CLLocationManager = CLLocationManager()
var source:MKMapItem?
var destination:MKMapItem?
var request:MKDirectionsRequest = MKDirectionsRequest()
var directions:MKDirections = MKDirections()
var directionsResponse:MKDirectionsResponse = MKDirectionsResponse()
var route:MKRoute = MKRoute()
override func viewDidLoad() {
super.viewDidLoad()
manager.requestAlwaysAuthorization()
map.mapType = MKMapType.Satellite
locMark = MKPlacemark(coordinate: CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude), addressDictionary: nil)
destMark = MKPlacemark(coordinate: CLLocationCoordinate2DMake(next.coordinate.latitude, next.coordinate.longitude), addressDictionary: nil)
source = MKMapItem(placemark: locMark)
destination = MKMapItem(placemark: destMark)
request.source = source
request.destination = destination
request.transportType = MKDirectionsTransportType.Automobile
request.requestsAlternateRoutes = true
directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler { (response:MKDirectionsResponse?, error:NSError?) -> Void in
if error == nil {
self.directionsResponse = response!
self.route = self.directionsResponse.routes[0] as! MKRoute
map.addOverlay(route.polyline, level: MKOverlayLevel.AboveRoads)
} else {
print(error)
}
}
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
print("redenrerForOverlay")
if(overlay.isKindOfClass(MKPolyline)) {
var renderer: MKPolylineRenderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = Colors.psnGreen
renderer.lineWidth = 5
return renderer
}
return nil
}
func mapView(mapView: MKMapView!, viewForOverlay overlay: MKOverlay!) -> MKOverlayView! {
print("ViewForOverlay")
if (overlay.isKindOfClass(MKPolyline)) {
var lineView: MKPolylineView = MKPolylineView(overlay: overlay)
lineView.backgroundColor = Colors.psnGreen
return lineView;
}
return nil;
}
}
Try changing the two lines to this:
request.source = source
request.destination = destination
Swift uses the property directly, rather than an explicit setter (which is only available in Obj-C).
I'm trying work with MapKit in Swift. I need to show the area of the map the current User Location and point of interest next to it, however these points of interest must have a different pattern of visualization User itself. I know that there is the need to implement the delegate of MapViewAnnotation, put in my code it does not run. Could someone help me with an example?
This is my code.
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let latArray = [-23.528657, -23.518514, -23.533796, -23.533796]
let longArray = [-46.484008, -46.486495, -46.495533, -46.476690]
var lat: CLLocationDegrees = -23.527096772791133
var long: CLLocationDegrees = -46.48964569157911
var latDelta: CLLocationDegrees = 0.01
var longDelta: CLLocationDegrees = 0.01
var theSpan: MKCoordinateSpan = MKCoordinateSpanMake(latDelta,longDelta)
var mypos: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat,long)
var myreg: MKCoordinateRegion = MKCoordinateRegionMake(mypos, theSpan)
self.mapView.setRegion(myreg, animated: true)
var myposannot = MKPointAnnotation()
myposannot.coordinate = mypos
myposannot.title = "Me"
myposannot.subtitle = "I am here!"
self.mapView.addAnnotation(myposannot)
for var i=0; i<4; ++i {
var latCli: CLLocationDegrees = latArray[i]
var longCli: CLLocationDegrees = longArray[i]
var myposCli : CLLocationCoordinate2D = CLLocationCoordinate2DMake(latCli,longCli)
var myposannotCli = MKPointAnnotation()
myposannotCli.coordinate = myposCli
myposannotCli.title = "Cliente" + " - " + String (i)
myposannotCli.subtitle = "Anotacao" + " - " + String (i)
self.mapView.addAnnotation(myposannotCli)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mapViewAnnot(mapViewAnnot: MKMapView!,ViewForAnnotation annotation: MKAnnotation!) ->MKAnnotationView{
if annotation is MKUserLocation{
return nil
}
let reuseId = "pin"
var pinView = mapViewAnnot.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if(pinView == nil){
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
pinView!.pinColor = .Red
pinView!.rightCalloutAccessoryView = UIButton.buttonWithType(.DetailDisclosure) as UIButton
} else {
pinView!.annotation = annotation
}
return pinView!
}
}
There are two main problems with the code:
The viewForAnnotation delegate method is not named correctly and so the map view will not call it. The method declaration which is currently this:
func mapViewAnnot(mapViewAnnot: MKMapView!,
ViewForAnnotation annotation: MKAnnotation!) ->MKAnnotationView {
is wrong. It should be this instead:
func mapView(mapView: MKMapView!,
viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
The method must be named mapView(mapView:viewForAnnotation:).
The other problem is this line:
var pinView = mapViewAnnot.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
The reference to some object named mapViewAnnot is meaningless and must be preventing the code from compiling. The line should be this:
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
import UIKit
import MapKit
class ViewController: UIViewController {
#IBOutlet weak var mapv: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapv.mapType = .satellite
let location = CLLocationCoordinate2D(latitude: 11.361516, longitude: 76.30274)
let span = MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
let region = MKCoordinateRegion(center: location, span: span)
mapv.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = "Edakkara"
annotation.subtitle = "Nilambur"
mapv.addAnnotation(annotation)