Add two coordinates in a button function to launch mapKit and start navigation between two points (Swift) - ios

I'm using this class
import UIKit
import CoreLocation
import GoogleMaps
import GooglePlaces
import SwiftyJSON
import Alamofire
import MapKit
class FinalClass: UIViewController {
#IBOutlet weak var containerView: UIView!
#IBOutlet weak var bottomInfoView: UIView!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var distanceLabel: UILabel!
var userLocation:CLLocationCoordinate2D?
var places:[QPlace] = []
var index:Int = -1
var locationStart = CLLocation()
var locationEnd = CLLocation()
var mapView:GMSMapView!
var marker:GMSMarker?
override func loadView() {
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
guard index >= 0, places.count > 0 else {
return
}
let place = places[index]
let lat = place.location?.latitude ?? 1.310844
let lng = place.location?.longitude ?? 103.866048
// Google map view
let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 12.5)
mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera)
mapView.autoresizingMask = [.flexibleHeight, .flexibleWidth, .flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin]
self.containerView.addSubview(mapView)
// Add gesture
addSwipeGesture()
didSelect(place: place)
if userLocation != nil {
addMarkerAtCurrentLocation(userLocation!)
}
}
func addSwipeGesture() {
let directions: [UISwipeGestureRecognizerDirection] = [.right, .left]
for direction in directions {
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:)))
gesture.direction = direction
self.bottomInfoView.addGestureRecognizer(gesture)
}
}
func addMarkerAtCurrentLocation(_ userLocation: CLLocationCoordinate2D) {
let marker = GMSMarker()
marker.position = userLocation
marker.title = "Your location"
marker.map = mapView
}
func didSelect(place:QPlace) {
guard let coordinates = place.location else {
return
}
// clear current marker
marker?.map = nil
// add marker
marker = GMSMarker()
marker?.position = coordinates
marker?.title = place.name
marker?.map = mapView
mapView.selectedMarker = marker
moveToMarker(marker!)
// update bottom info panel view
let desc = place.getDescription()
descriptionLabel.text = desc.characters.count > 0 ? desc : "-"
distanceLabel.text = "-"
// update distance
if userLocation != nil {
let dist = distance(from: userLocation!, to: coordinates)
distanceLabel.text = String.init(format: "Distance %.2f meters", dist)
self.drawPath(startLocation: userLocation!, endLocation: coordinates)
}
title = place.name
}
func moveToMarker(_ marker: GMSMarker) {
let camera = GMSCameraPosition.camera(withLatitude: marker.position.latitude,
longitude: marker.position.longitude,
zoom: 12.5)
self.mapView.animate(to: camera)
}
// distance between two coordinates
func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
let to = CLLocation(latitude: to.latitude, longitude: to.longitude)
return from.distance(from: to)
}
func handleSwipe(sender: UISwipeGestureRecognizer) {
guard index >= 0, places.count > 0 else {
return
}
if sender.direction == .left {
if index < places.count - 2 {
index += 1
didSelect(place: places[index])
}
} else if sender.direction == .right {
if index > 1 {
index -= 1
didSelect(place: places[index])
}
}
}
func drawPath(startLocation: CLLocationCoordinate2D, endLocation: CLLocationCoordinate2D) {
let from = CLLocation(latitude: startLocation.latitude, longitude: startLocation.longitude)
let to = CLLocation(latitude: endLocation.latitude, longitude: endLocation.longitude)
let origin = "\(from.coordinate.latitude),\(from.coordinate.longitude)"
let destination = "\(to.coordinate.latitude),\(to.coordinate.longitude)"
let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving"
Alamofire.request(url).responseJSON { response in
print(response.request as Any) // original URL request
print(response.response as Any) // HTTP URL response
print(response.data as Any) // server data
print(response.result as Any) // result of response serialization
let json = JSON(data: response.data!)
let routes = json["routes"].arrayValue
// print route using Polyline
for route in routes
{
let routeOverviewPolyline = route["overview_polyline"].dictionary
let points = routeOverviewPolyline?["points"]?.stringValue
let path = GMSPath.init(fromEncodedPath: points!)
let polyline = GMSPolyline.init(path: path)
polyline.strokeWidth = 4
polyline.strokeColor = UIColor.black
polyline.map = self.mapView
}
}
}
#IBAction func navigationStart(_ sender: Any) {
}
with a google maps to add place markers, draw the direction on the map and show the distance between two points, now i would like to launch the navigator between startLocation: userLocation! and endLocation: coordinates but with some research i saw that i can not launch the navigator in the same view, i need to open the maps application, so i decided to add the MapKit and a button
#IBAction func navigationStart(_ sender: Any) {
}
so how can i do that by pressing the button the map application opens with direction from userLocation to coordinates ? I already looked to similar question but is a little different to my problem, because i already have the points but in different format.

Your question is a little confusing but if you want to open the maps app and show direction from a user's current location to another point on the map then you don't need to pass the user's location, just the destination:
Swift 4:
let coordinate = CLLocationCoordinate2DMake(51.5007, -0.1246)
let placeMark = MKPlacemark(coordinate: coordinate)
let mapItem = MKMapItem(placemark: placeMark)
mapItem.name = "Big Ben"
mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
Objective C:
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(51.5007, -0.1246);
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate: coordinate];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:#"Big Ben"];
[mapItem openInMapsWithLaunchOptions:#{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving}];

Related

How can I draw a polyline in ARKit using latitude and longitude?

Currently I can render the spheres using latitude and longitude in ARKit Geolocation Tracking , can anyone please guide me how can I draw polyline between 2 CLLocation in ARKit .
here is a full code to create poly line between two points and also set a width and color of that poly line
var locManager = CLLocationManager()
var currentLocation: CLLocation!
let annotation = MKPointAnnotation()
let annotation2 = MKPointAnnotation()
// MARK:- DRIVER -
var driverLatitute:String!
var driverLongitude:String!
// MARK:- RESTAURANT -
var restaurantLatitude:String!
var restaurantLongitude:String!
IN VIEW DID LOAD
// MARK:- 1 ( MAP ) -
self.locManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
self.locManager.delegate = self
self.locManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.locManager.startUpdatingLocation()
print("UPDATE UPDATE")
}
if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways) {
print("")
}
DELEGATE METHODS
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//print("**********************")
//print("Long \(manager.location!.coordinate.longitude)")
//print("Lati \(manager.location!.coordinate.latitude)")
//print("Alt \(manager.location!.altitude)")
//print("Speed \(manager.location!.speed)")
//print("Accu \(manager.location!.horizontalAccuracy)")
//print("**********************")
//print(Double((vendorLatitute as NSString).doubleValue))
//print(Double((vendorLongitute as NSString).doubleValue))
/*
// restaurant
self.restaurantLatitude = (dict["deliveryLat"] as! String)
self.restaurantLongitude = (dict["deliveryLong"] as! String)
// driver
self.driverLatitute = (dict["resturentLatitude"] as! String)
self.driverLongitude = (dict["resturentLongitude"] as! String)
*/
let restaurantLatitudeDouble = Double(self.restaurantLatitude)
let restaurantLongitudeDouble = Double(self.restaurantLongitude)
let driverLatitudeDouble = Double("\(manager.location!.coordinate.latitude)") //Double(self.driverLatitute)
let driverLongitudeDouble = Double("\(manager.location!.coordinate.longitude)") // Double(self.driverLongitude)
let coordinate₀ = CLLocation(latitude: restaurantLatitudeDouble!, longitude: restaurantLongitudeDouble!)
let coordinate₁ = CLLocation(latitude: driverLatitudeDouble!, longitude: driverLongitudeDouble!)
/************************************** RESTAURANT LATITUTDE AND LONGITUDE ********************************/
// first location
let sourceLocation = CLLocationCoordinate2D(latitude: restaurantLatitudeDouble!, longitude: restaurantLongitudeDouble!)
/********************************************************************************************************************/
/************************************* DRIVER LATITUTDE AND LINGITUDE ******************************************/
// second location
let destinationLocation = CLLocationCoordinate2D(latitude: driverLatitudeDouble!, longitude: driverLongitudeDouble!)
/********************************************************************************************************************/
//print(sourceLocation)
//print(destinationLocation)
let sourcePin = customPin(pinTitle: "You", pinSubTitle: "", location: sourceLocation)
let destinationPin = customPin(pinTitle: "Driver", pinSubTitle: "", location: destinationLocation)
/***************** REMOVE PREVIUOS ANNOTATION TO GENERATE NEW ANNOTATION *******************************************/
self.mapView.removeAnnotations(self.mapView.annotations)
/********************************************************************************************************************/
self.mapView.addAnnotation(sourcePin)
self.mapView.addAnnotation(destinationPin)
let sourcePlaceMark = MKPlacemark(coordinate: sourceLocation)
let destinationPlaceMark = MKPlacemark(coordinate: destinationLocation)
let directionRequest = MKDirections.Request()
directionRequest.source = MKMapItem(placemark: sourcePlaceMark)
directionRequest.destination = MKMapItem(placemark: destinationPlaceMark)
directionRequest.transportType = .automobile
let directions = MKDirections(request: directionRequest)
directions.calculate { [self] (response, error) in
guard let directionResonse = response else {
if let error = error {
print("we have error getting directions==\(error.localizedDescription)")
}
return
}
/***************** REMOVE PREVIUOS POLYLINE TO GENERATE NEW POLYLINE *******************************/
let overlays = self.mapView.overlays
self.mapView.removeOverlays(overlays)
/************************************************************************************/
/***************** GET DISTANCE BETWEEN TWO CORDINATES *******************************/
let distanceInMeters = coordinate₀.distance(from: coordinate₁)
// print(distanceInMeters as Any)
// remove decimal
let distanceFloat: Double = (distanceInMeters as Any as! Double)
// print(distanceFloat as Any)
// self.lblDistance.text = (String(format: "Distance : %.0f Miles away", distanceFloat/1609.344))
self.lblTotalDistance.text = (String(format: "Distance : %.0f Miles away", distanceFloat/1609.344))
// print(distanceFloat/1609.344)
// print(String(format: "Distance : %.0f Miles away", distanceFloat/1609.344))
let s:String = String(format: "%.0f",distanceFloat/1609.344)
// print(s as Any)
/************************************************************************************/
/***************** GENERATE NEW POLYLINE *******************************/
let route = directionResonse.routes[0]
self.mapView.addOverlay(route.polyline, level: .aboveRoads)
let rect = route.polyline.boundingMapRect
self.mapView.setRegion(MKCoordinateRegion(rect), animated: true)
/************************************************************************************/
}
self.mapView.delegate = self
print("update location after 5 sec")
// self.locManager.stopUpdatingLocation()
// speed = distance / time
}
// line width of poly line
//MARK:- MapKit delegates -
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.blue
renderer.lineWidth = 4.0
return renderer
}

How can I compare if I select my location in Swift?

I have created an application that contains a mapView. I added a couple of annotations around my location. I want when I click on an annotation to show me the title in a label.
I did that and I took the title and put it in myLabel but when I'm clicking on my location, the application stops working and I get the error:
(Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value)
Here is my code:
import UIKit
import MapKit
import CoreLocation
import Foundation
class ViewControllermap: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mymap: MKMapView!
#IBOutlet weak var viewaddress: UILabel!
var selectedAnnotation: MKPointAnnotation?
var locationManager: CLLocationManager = CLLocationManager()
let regionInMeters:Double = 3000
var previouslocation: CLLocation?
var longitudeLocation:String = ""
var latituseLocation:String = ""
override func viewDidLoad() {
mymap.delegate = self
// checkLocationSevices()
super.viewDidLoad()
if let location = locationManager.location?.coordinate
{
let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
mymap.setRegion(region, animated: true)
}
mymap.showsUserLocation = true
let location = CLLocationCoordinate2DMake(35.1623, 33.3178)
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = "P1"
annotation.subtitle = "28 oct street"
mymap.addAnnotation(annotation)
let location2 = CLLocationCoordinate2DMake(35.1658, 33.3147)
let annotation2 = MKPointAnnotation()
annotation2.coordinate = location2
annotation2.title = "P2"
annotation2.subtitle = " Makedonitissis 46, Nicosia 2417"
mymap.addAnnotation(annotation2)
let location3 = CLLocationCoordinate2DMake(35.1600, 33.3770)
let annotation3 = MKPointAnnotation()
annotation3.coordinate = location3
annotation3.title = "P3"
annotation3.subtitle = " Kallipoleos 75, Nicosia 1678"
mymap.addAnnotation(annotation3)
let location4 = CLLocationCoordinate2DMake(35.1602, 33.3390)
let annotation4 = MKPointAnnotation()
annotation4.coordinate = location4
annotation4.title = "P4"
annotation4.subtitle = "Diogenis Str 6 Nicosia CY, 2404"
mymap.addAnnotation(annotation4)
let location5 = CLLocationCoordinate2DMake(35.1673, 33.3277)
let annotation5 = MKPointAnnotation()
annotation5.coordinate = location5
annotation5.title = "P5"
annotation5.subtitle = "Neas Egkomis 4, Egkomi"
mymap.addAnnotation(annotation5)
let location6 = CLLocationCoordinate2DMake(35.1680, 33.3375)
let annotation6 = MKPointAnnotation()
annotation6.coordinate = location6
annotation6.title = "P6"
annotation6.subtitle = "Neas Egkomis 4, Egkomi"
mymap.addAnnotation(annotation6)
let location7 = CLLocationCoordinate2DMake(35.1460, 33.3357)
let annotation7 = MKPointAnnotation()
annotation7.coordinate = location7
annotation7.title = "P7"
annotation7.subtitle = "Neas Egkomis 4, Egkomi"
mymap.addAnnotation(annotation7)
let location8 = CLLocationCoordinate2DMake(35.1580, 33.3275)
let annotation8 = MKPointAnnotation()
annotation8.coordinate = location8
annotation8.title = "P8"
annotation8.subtitle = "Neas Egkomis 4, Egkomi"
mymap.addAnnotation(annotation8)
// Do any additional setup after loading the view.
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let annotationCoordinate = view.annotation?.coordinate {
self.selectedAnnotation = view.annotation as? MKPointAnnotation
viewaddress.text = "\(selectedAnnotation!.subtitle!)" as String
}
}
}
This error happens just when I click on my location and code is working for other annotations.
Anyone know how can I fix this?
Your selectedAnotation or its subtitle is nil .. thats why you are getting this crash ... use optional chaining or optional binding to avoid this ..
Roughly something like this ... // not tested code
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let annotationCoordinate = view.annotation?.coordinate {
self.selectedAnnotation = view.annotation as? MKPointAnnotation
if let annnotation = selectedAnnotation , let subTitle = annnotation.subTitle as? String {
viewaddress.text = "\(subTitle)"
}
}
}

Draw route on map in swift 4

I want draw route between two coordinates in swift4.
and I am using this code,
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var myMap: MKMapView!
var myRoute : MKRoute!
override func viewDidLoad() {
super.viewDidLoad()
let point1 = MKPointAnnotation()
let point2 = MKPointAnnotation()
point1.coordinate = CLLocationCoordinate2DMake(25.0305, 121.5360)
point1.title = "Taipei"
point1.subtitle = "Taiwan"
myMap.addAnnotation(point1)
point2.coordinate = CLLocationCoordinate2DMake(24.9511, 121.2358)
point2.title = "Chungli"
point2.subtitle = "Taiwan"
myMap.addAnnotation(point2)
myMap.centerCoordinate = point2.coordinate
myMap.delegate = self
//Span of the map
myMap.setRegion(MKCoordinateRegionMake(point2.coordinate, MKCoordinateSpanMake(0.7,0.7)), animated: true)
let directionsRequest = MKDirectionsRequest()
let markTaipei = MKPlacemark(coordinate: CLLocationCoordinate2DMake(point1.coordinate.latitude, point1.coordinate.longitude), addressDictionary: nil)
let markChungli = MKPlacemark(coordinate: CLLocationCoordinate2DMake(point2.coordinate.latitude, point2.coordinate.longitude), addressDictionary: nil)
directionsRequest.source = MKMapItem(placemark: markChungli)
directionsRequest.destination = MKMapItem(placemark: markTaipei)
directionsRequest.transportType = MKDirectionsTransportType.automobile
let directions = MKDirections(request: directionsRequest)
directions.calculate(completionHandler: {
response, error in
if error == nil {
self.myRoute = response!.routes[0] as MKRoute
self.myMap.add(self.myRoute.polyline)
}
})
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) ->MKOverlayRenderer {
let myLineRenderer = MKPolylineRenderer(polyline: myRoute.polyline)
myLineRenderer.strokeColor = UIColor.red
myLineRenderer.lineWidth = 3
return myLineRenderer
}
}
and this code give me right answer
But when I change coordinates then it not show route.
new coordinates are
point1 = 26.9124, 75.7873
point2 = 26.9124, 76.7873
Looks like Apple Maps doesn't yet support India. (quora.com/…) I guess if this is a critical part of your app, you may have to consider Google Maps
Those new coordinates are in India, and it just looks like directions are not available there. I get an error that says "Error Domain=MKErrorDomain Code=4 "Directions Not Available" UserInfo={NSLocalizedDescription=Directions Not Available, MKErrorGEOError=-8, MKErrorGEOErrorUserInfo={ }, MKErrorGEOTransitIncidentKey=<_GEOTransitRoutingIncidentMessage: 0x60800023df20>, MKDirectionsErrorCode=0, NSLocalizedFailureReason=Directions are not available between these locations.}"
Thanx Rob for this answar.

How to display time on route as google maps

I have created route with multiple annotations.
I want to display text between annotations which exactly as attached screen shot.
Can any one help please?
Thanks
I tried something which will show the distance between two annotation but not when you tap on the MKPolylineOverlay. One more important thing I am not maintaining any standards.
Here is my controller structure.
import UIKit
import MapKit
class RouteViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
//Rest of the code see below
}
First of all I'll add some annotation to map in the viewDidLoad delegate method as below.
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
let annotation1 = MKPointAnnotation()
annotation1.title = "Times Square"
annotation1.coordinate = CLLocationCoordinate2D(latitude: 40.759011, longitude: -73.984472)
let annotation2 = MKPointAnnotation()
annotation2.title = "Empire State Building"
annotation2.coordinate = CLLocationCoordinate2D(latitude: 40.748441, longitude: -73.985564)
let annotation3 = MKPointAnnotation()
annotation3.title = "Some Point"
annotation3.coordinate = CLLocationCoordinate2D(latitude: 40.7484, longitude: -73.97)
let arrayOfPoints = [ annotation1, annotation2, annotation3]
self.mapView.addAnnotations(arrayOfPoints)
self.mapView.centerCoordinate = annotation2.coordinate
for (index, annotation) in arrayOfPoints.enumerate() {
if index < (arrayOfPoints.count-1) {
//I am taking the two consecutive annotation and performing the routing operation.
self.directionHandlerMethod(annotation.coordinate, ePoint: arrayOfPoints[index+1].coordinate)
}
}
}
In the directionHandlerMethod, I am performing the actual request for direction as below,
func directionHandlerMethod(sPoint: CLLocationCoordinate2D, ePoint: CLLocationCoordinate2D) {
let sourcePlacemark = MKPlacemark(coordinate: sPoint, addressDictionary: nil)
let destinationPlacemark = MKPlacemark(coordinate: ePoint, addressDictionary: nil)
let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
let directionRequest = MKDirectionsRequest()
directionRequest.source = sourceMapItem
directionRequest.destination = destinationMapItem
directionRequest.transportType = .Automobile
let directions = MKDirections(request: directionRequest)
directions.calculateDirectionsWithCompletionHandler {
(response, error) -> Void in
guard let response = response else {
if let error = error {
print("Error: \(error)")
}
return
}
//I am assuming that it will contain one and only one result so I am taking that one passing to addRoute method
self.addRoute(response.routes[0])
}
}
Next I am adding the polyline route on map in the addRoute method as below,
func addRoute(route: MKRoute) {
let polyline = route.polyline
//Here I am taking the centre point on the polyline and placing an annotation by giving the title as 'Route' and the distance in the subtitle
let annoatation = MKPointAnnotation()
annoatation.coordinate = MKCoordinateForMapPoint(polyline.points()[polyline.pointCount/2])
annoatation.title = "Route"
let timeInMinute = route.expectedTravelTime / 60
let distanceString = String.localizedStringWithFormat("%.2f %#", timeInMinute, timeInMinute>1 ? "minutes" : "minute")
annoatation.subtitle = distanceString
self.mapView.addAnnotation(annoatation)
self.mapView.addOverlay(polyline)
}
Next I am implementing the rendererForOverlay delegate method as below,
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.blueColor()
renderer.lineWidth = 2
renderer.lineCap = .Butt
renderer.lineJoin = .Round
return renderer
}
Next one is the important one delegate method which is viewForAnnotation. Here I am doing some things like placing the label instead of the annotation as below,
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation.title != nil && annotation.title!! == "Route" {
let label = UILabel()
label.adjustsFontSizeToFitWidth = true
label.backgroundColor = UIColor.whiteColor()
label.minimumScaleFactor = 0.5
label.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
label.text = annotation.subtitle ?? ""
let view = MKAnnotationView()
view.addSubview(label)
return view
}
return nil
}

How can I add a GPS that leads to pins on map?

I am making an app that displays pins ( that the user adds) on a map and saves them in a tableview and I would like to have a GPS lead the user when they tap on a button that opens the GPS so they can get to that place, how could I do this, this is the code I have in the table view:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = places[indexPath.row]["name"]
return cell
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
activePlace = indexPath.row
return indexPath
}
and this is the code I have in the map view:
func action(gestureRecognizer:UIGestureRecognizer) {
if gestureRecognizer.state == UIGestureRecognizerState.Began {
var touchPoint = gestureRecognizer.locationInView(self.Map)
var newCoordinate = self.Map.convertPoint(touchPoint, toCoordinateFromView: self.Map)
var location = CLLocation(latitude: newCoordinate.latitude , longitude: newCoordinate.longitude)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
var title = ""
if (error == nil) {
if let p = CLPlacemark(placemark: placemarks?[0] as! CLPlacemark) {
var subThoroughfare: String = ""
var thoroughfare: String = ""
if p.subThoroughfare != nil {
subThoroughfare = p.subThoroughfare
}
if p.thoroughfare != nil {
thoroughfare = p.thoroughfare
}
title = "\(subThoroughfare) \(thoroughfare)"
}
}
if title == "" {
title = "added \(NSDate())"
}
places.append(["name":title,"lat":"\(newCoordinate.latitude)","lon":"\(newCoordinate.longitude)"])
I have been trying the code below to add the GPS but I have a predefined destination so I suppose I have to change the coordinates to something else but I dont know exactly what, thanks for the help !
UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/maps?daddr=34.539250,-117.222025")!)
I am also using this piece of code for the user location
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var userLocation:CLLocation = locations[0] as! CLLocation
var latitude = userLocation.coordinate.latitude
var longitude = userLocation.coordinate.longitude
var coordinate = CLLocationCoordinate2DMake(latitude, longitude)
var latDelta:CLLocationDegrees = 0.01
var lonDelta:CLLocationDegrees = 0.01
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
var region:MKCoordinateRegion = MKCoordinateRegionMake(coordinate, span)
self.Map.setRegion(region, animated: true)
To piggyback off of #Mingebag 's answer, in response to your comment there:
You need to set the variables in the openMapForPlace() method he provided to the ones that correspond to the gps position you want to get directions to in the apple maps app.
Wherever you call this method, you can pass it the variables you need. For this to work, you really just need to give it Lat / Lon somehow.
You could do that by making it be:
func openMapsForPlace(lat: Double, lon: Double) {}
or whatever format you have those in.
You can also just put this code wherever you want if you have a better place for it to execute from:
let regionDistance:CLLocationDistance = 10000
//set the coordinates with your variables
var coordinates = CLLocationCoordinate2DMake(newCoordinates.latitude, newCoordinates.longitude)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
var options = [
MKLaunchOptionsMapCenterKey: NSValue(MKCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(MKCoordinateSpan: regionSpan.span)
]
//now your placemark will have the lat long you put in above
var placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
var mapItem = MKMapItem(placemark: placemark)
mapItem.name = "\(self.venueName)"
//this line then launches the app for you
mapItem.openInMapsWithLaunchOptions(options)
Let us assume you have location enabled so you just need the "user location" that you have saved in your table then try this:
Just pass your lang,lat and that should do it ^^
func openMapForPlace() {
var lat1 : NSString = self.venueLat
var lng1 : NSString = self.venueLng
var latitute:CLLocationDegrees = lat1.doubleValue
var longitute:CLLocationDegrees = lng1.doubleValue
let regionDistance:CLLocationDistance = 10000
var coordinates = CLLocationCoordinate2DMake(latitute, longitute)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
var options = [
MKLaunchOptionsMapCenterKey: NSValue(MKCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(MKCoordinateSpan: regionSpan.span)
]
var placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
var mapItem = MKMapItem(placemark: placemark)
mapItem.name = "\(self.venueName)"
mapItem.openInMapsWithLaunchOptions(options)
}
If there are any question feel free to ask

Resources