Firebase database now only displaying newly added annotations on map - ios

I have an app that allows people to put annotations on a map that get stored in a Firebase database, I have recently been trying to add a new feature to the app so to avoid messing about with my real database I created another app in firebase and used it for me to do my testing on. I deleted the GoogleService-Info.Plist and imported the one for the new test app but now when I delete the test GoogleService-Info.Plist and replace it with the one that works with my Live app none of my annotations show up on the map, but any I create from that point onwards will show up.
I've done a clean and build but still the same result. All the data is still there in my original database as my AppStore version of the app works exactly as it should, I really don't know what could be wrong here, I'll let you see what my code is for retrieving the annotations, in case that helps you with your answer.
import UIKit
import MapKit
import Firebase
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
#IBOutlet weak var postboxesLoggedLabel: UILabel!
var locationManager = CLLocationManager()
let annotation = MKPointAnnotation()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
displayAnnotations()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0]
let latitude = userLocation.coordinate.latitude
let longitude = userLocation.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
locationManager.stopUpdatingLocation()
}
func displayAnnotations() {
let ref = Database.database().reference()
ref.child("Postbox").observe(.childAdded, with: { (snapshot) in
let monToFri = (snapshot.value as AnyObject!)!["Monday to Friday Collection Time"] as! String!
let sat = (snapshot.value as AnyObject!)!["Saturday Collection Time"] as! String!
let latitude = (snapshot.value as AnyObject!)!["Latitude"] as! String!
let longitude = (snapshot.value as AnyObject!)!["Longitude"] as! String!
let lastCollection = "Mon - Fri: \(monToFri!)" + " Sat: \(sat!)"
self.annotation.coordinate = CLLocationCoordinate2D(latitude: (Double(latitude!))!, longitude: (Double(longitude!))!)
self.annotation.title = "Last Collection:"
self.annotation.subtitle = lastCollection
self.mapView.addAnnotation(self.annotation)
self.postboxesLoggedLabel.text = String(self.mapView.annotations.count)
})
}
/* func removeAnnotation(gesture: UIGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.ended {
self.mapView.removeAnnotation(annotation)
print("Annotation Removed")
}
} */
#IBAction func myLocation(_ sender: Any) {
locationManager.startUpdatingLocation()
}
#IBAction func mapType(_ sender: Any) {
switch ((sender as AnyObject).selectedSegmentIndex) {
case 0:
mapView.mapType = .standard
case 1:
mapView.mapType = .satellite
default: // or case 2
mapView.mapType = .hybrid
}
}
}

Related

mapView: GMSMapView! nil causing the app to crash (swift)

I'm completely new when it comes to use Google Maps SKD for iOS and I have the following problem: My app uses Firebase and the MapVC is the first VC if the user is logged in. I set a UIVIew in the storyboard with the size I wanted and made its class GMSMapView. I also use the CLLocation Manager and the location comes ok, I pass it on to the camera variable and it's fine. But if add this code: mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) or this code: self.mapView.camera = camera the app crashes because mapView is nil. If I don't add those lines of code, the map shown is just the default map (Europe). What I need is the map camera to show the location I'm getting from CLLocation and updates it on the map as the location changes as well.
My code for the MapVC is below:
import UIKit
import GoogleMaps
import GooglePlaces
import CoreLocation
import Alamofire
import Firebase
import FirebaseFirestore
class AlertaVC: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var alertaBtn: RoundButton!
var latitude: CLLocationSpeed?
var longitude: CLLocationDegrees?
var mapView: GoogleMaps.GMSMapView!
var db: Firestore!
var userID: String?
var nameUser: Any?
let locationManager = CLLocationManager()
#IBAction func dispararAlertaBtn(_ sender: UIButton) {
//changing the title and color after the alert is sent
alertaBtn.isSelected = !alertaBtn.isSelected
if alertaBtn.isSelected {
//setting up twilio to send the alert SMS
let headers: HTTPHeaders = [
"Content-Type": "application/x-www-form-urlencoded"
]
//add the phone numbers from the firebase document
let parameters: Parameters = [
"To": "phone-number",
"Body": "Ola, to enviando SMS!"
]
//change the SMS body to include the user's name and the link with live location
AF.request("https://url.twil.io/smsAlerta", method: .post, parameters: parameters, headers: headers).responseJSON { response in
print(response.response as Any, "response alamofire")
}
alertaBtn.setTitle("Encerrar alerta!", for: .normal)
alertaBtn.backgroundColor = UIColor(red: 0.83529, green: 0.4, blue: 0.5725490196, alpha: 1.0)
} else {
alertaBtn.setTitle("Disparar alerta!", for: .normal)
alertaBtn.backgroundColor = UIColor(red: 0.3254, green: 0.1921, blue: 0.2627, alpha: 1.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
db = Firestore.firestore()
let user = Auth.auth().currentUser
if let user = user {
// The user's ID, unique to the Firebase project.
self.userID = user.uid
print(self.userID!, "user ID firebase")
}
}
override func viewWillAppear(_ animated: Bool) {
//showCurrentLocation() Tried calling the function #ViewWillAppear but it didn't work either
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
latitude = locValue.latitude
longitude = locValue.longitude
let camera: GMSCameraPosition = GMSCameraPosition.camera(withLatitude: latitude ?? 19.741755, longitude: longitude ?? -155.844437, zoom: 7.0) //if doesnt load will show Hawaii
print(camera as Any, "camera") <-- WORKS FINE: GMSCameraPosition 0x600000f389f0: target:(37.332, -122.031) bearing:0.000 zoomLevel:7.000 viewingAngle:0.000 camera
self.mapView.camera = camera <<--- CRASHES HERE: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
self.mapView?.animate(to: camera) <<-- WITHOUT THE LINE ABOVE THIS ANIMATION DOESN`T HAPPEN, BECAUSE MAPVIEW IS NIL
print("locations = \(latitude ?? 56.56), \(longitude ?? 45.45)")
}
func showCurrentLocation() { <<- NOT BEING CALLED, BUT IF IT IS, CRASHES
//mapView.settings.myLocationButton = true
let locationObj = locationManager.location!
let coord = locationObj.coordinate
let lattitude = coord.latitude
let longitude = coord.longitude
print(" lat in updating \(lattitude) ")
print(" long in updating \(longitude)")
let center = CLLocationCoordinate2D(latitude: locationObj.coordinate.latitude, longitude: locationObj.coordinate.longitude)
let marker = GMSMarker()
marker.position = center
marker.title = "current location"
marker.map = mapView
let camera: GMSCameraPosition = GMSCameraPosition.camera(withLatitude: lattitude, longitude: longitude, zoom: 7.0)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) <-- CRASHES HERE
self.mapView.animate(to: camera)
}
func fetchUserName(userId: String) {
db.collection("Usuarias").document(self.userID!).getDocument() {
(document, err) in
if let document = document, document.exists {
let dataDescription = document.data()!["Nome"] ?? "nil"
print("Document data: \(dataDescription)")
self.nameUser = dataDescription
print(self.nameUser as Any, "dentro do fetch")
} else {
print("Document does not exist")
}
}
}
}
I'd appreciate any help. Thanks =)
If you've created the 'View' in storyboard and assign as 'GMSMapView' you should add it as 'IBOutlet' in ViewController, you can do it by clicking 'Option' on keyboard and drag from map to ViewController like you've add 'alertaBtn', if you want to create map programmatically you need to initiate it in 'viewDidLoad' method then use it to set camera or to do other changes.

Display the distance from user with mapKit Swift (miles/km)

I have been attempting to display the distance on a tableView but I am unable to get it to happen. This question follows up from this question: CLLocationDistance conversion. I have checked the distance. Using this function in my Location class:
// Get distance
func distance(to location: CLLocation) -> CLLocationDistance {
return location.distance(from: self.location)
}
How I get the users current location:
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)
mapView.setRegion(region, animated: true)
// Add a lastUserLocation to LocationManager and update it every time that the delegate receives a new location
LocationManager.shared.lastUserLocation = locations.last
LocationManager.shared.sortLocationsInPlace()
self.mapView.showsUserLocation = true
}
Sort function in LocationManager:
func getSortedLocations(userLocation: CLLocation) -> [Location] {
return locations.sorted { (l1, l2) -> Bool in
return l1.distance(to: userLocation) < l2.distance(to: userLocation)
}
}
func sortLocationsInPlace() {
if let validLocation = lastUserLocation {
locations.sort { (l1, l2) -> Bool in
return l1.distance(to: validLocation) < l2.distance(to: validLocation)
}
}
}
cellForRowAt:
var sortedLocations = [Location]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "locationCell", for: indexPath)
let location = sortedLocations[indexPath.row]
cell.textLabel?.text = location.name
return cell
}
Update
Inside Location class:
class Location {
var name: String
var latitude: Double
var longitude: Double
var location:CLLocation {
return CLLocation(latitude: latitude, longitude: longitude)
}
init?(json: JSON) {
guard let name = json["name"] as? String, let latitude = json["latitude"] as? Double, let longitude = json["longitude"] as? Double else { return nil }
self.name = name
self.latitude = latitude
self.longitude = longitude
}
func distance(to location: CLLocation) -> CLLocationDistance {
return location.distance(from: self.location)
}
}
Considering your code, I am making some assumptions:
Your sortedLocations array has different locations that you extracted from a JSON or whatever.
You call startUpdatingLocation() or similar somewhere before loading your data.
You are receiving updates in your didUpdateLocations.
Your LocationManager keeps an ordered copy of all your locations in a variable called locations, the one you are ordering inside didUpdateLocations.
That considered, what I understand you want to do is to display your sortedLocations ordered according to a reference location.
What is missing is to update your UITableView data once your user location is received. You have two main options:
To only load your UITableView once you have already your first user location retrieved by didUpdateLocations.
To force a UITableView update once you get a new location, by calling tableView.reloadData() inside didUpdateLocations. This will redraw your list every time you receive a location update, sorting them by location.
However, in any of those cases you need to replace your cellForRow text to display your distance instead of location.name:
// Distance in meters
cell.textLabel?.text = String(location.distance(to: LocationManager.shared.lastUserLocation!))
// Distance in miles
cell.textLabel?.text = String(location.distance(to: LocationManager.shared.lastUserLocation!)*0.00062137)
And update your didUpdateLocations:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
mapView.setRegion(region, animated: true)
// Add a lastUserLocation to LocationManager and update it every time that the delegate receives a new location
LocationManager.shared.lastUserLocation = location
LocationManager.shared.sortLocationsInPlace()
sortedLocations = LocationManager.shared.locations
tableView.reloadData()
self.mapView.showsUserLocation = true
}
}
With your current code you are comparing all distances with a self.location variable that its not being initialised anywhere apparently.

swift: what is the correct way of working with current location

I am quite new to swift and IOS development.
I would like to ask experienced members what is the correct way of creating mapvie and tableview in one viewcontroller and populating them.
The logic of application is the following:
get current location of user
read plist file with POI coordinates
for each POI run a function wich calculates distance between user and point
populate table with data from plist file plus newly calculated data.
Both mapview and tableview are in the same viewcontroller.
in viewDidLoad I am getting users location.
in viewwillappear I am running functions to read plist file and calculate distances between POIs and user.
Everything is working but it is not stable ... sometimes it might show user's location but table will be empty. So I doubt that I am doing everything correctly. Also probably it is not correct to put both map and table inside one class?
Update
Here is the code:
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var theMapView: MKMapView!
#IBOutlet weak var tableView: UITableView!
var locationManager: CLLocationManager!
var branches = [Branch]()
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
tableView.dataSource = self
tableView.delegate = self
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
//mapview setup to show user location
theMapView.delegate = self
theMapView.showsUserLocation = true
theMapView.mapType = MKMapType(rawValue: 0)!
theMapView.userTrackingMode = MKUserTrackingMode(rawValue: 2)!
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
readFromPlist()
}
//MARK: UITableView methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return branches.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MapCustomCell = tableView.dequeueReusableCellWithIdentifier("mapCell") as! MapCustomCell
let brnch = branches[indexPath.row]
cell.mapSetupCell(brnch.cityName, AddressLabel: brnch.address, DistanceLabel: brnch.distance)
return cell
}
//MARK: FUNC TO CALCULATE DISTANCE
func calculateDistance (lat1 lat1: Double, lon1: Double, lat2: Double, lon2: Double) -> String {
return "100km"
}
func locationManager (manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let myCoordinates = locations.last
let myLat = myCoordinates!.coordinate.latitude
let myLong = myCoordinates!.coordinate.longitude
let myCoordinates2D = CLLocationCoordinate2DMake(myLat, myLong)
let myLatDelta = 0.10
let myLongDelta = 0.10
let mySpan = MKCoordinateSpanMake(myLatDelta, myLongDelta)
let myRegion = MKCoordinateRegion(center: myCoordinates2D, span: mySpan)
theMapView.setRegion(myRegion, animated: true)
let myAnno = MKPointAnnotation()
myAnno.coordinate = myCoordinates2D
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("error:" + error.localizedDescription)
}
func readFromPlist() {
//read plist file to extract banks coordinates
let path = NSBundle.mainBundle().pathForResource("poi", ofType: "plist")
let POIarrays = NSArray(contentsOfFile: path!)
for arr in POIarrays! {
var ctName : String!
var brnchAddress : String!
var wrkngHours : String!
var lat : Double!
var long : Double!
ctName = arr.objectForKey("cityName")! as! String
brnchAddress = arr.objectForKey("address")! as! String
wrkngHours = arr.objectForKey("workingHours")! as! String
lat = Double(arr.objectForKey("latitude")! as! String)
long = Double(arr.objectForKey("longitude")! as! String)
let latitude: CLLocationDegrees = lat
let longitude : CLLocationDegrees = long
let bankLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let annotation = MKPointAnnotation()
annotation.coordinate = bankLocation
annotation.title = bnkName
annotation.subtitle = brnchAddress
self.theMapView.addAnnotation(annotation)
let myLatitude = self.locationManager.location?.coordinate.latitude
let myLongitude = self.locationManager.location?.coordinate.longitude
if myLatitude != nil {
let dist = calculateDistance(lat1: latitude, lon1: longitude, lat2: myLatitude!, lon2: myLongitude!)
let b = Branch(cityName: ctName!, address: brnchAddress!, distance: dist)
branches.append(b)
}
}
}
}
Sometimes I got an error "error:The operation couldn’t be completed. (kCLErrorDomain error 0.)" and current location doesn't appear on my map.

How to calculate the distance between my current location and other Pins in MapView

I am new to Swift and I need to calculate the nearest places around my current location. Would you advice me which function should I use to calculate the distance between my location and the nearest around me. I have to display the distance and the places in the app,so that the user can choose which one fits best for him.I think I should use latitude and longitude coordinates which can be compared with mine. I also found out that I have to use distanceFromLocation , but I do not know how and I would be glad if someone provide me with an example which I can use for my code.
My code so far is:
class ViewThree: UIViewController, CLLocationManagerDelegate{
#IBOutlet weak var SegmentControl: UISegmentedControl!
#IBOutlet weak var Mapview: MKMapView!
var manager = CLLocationManager()
var receiveImeNaSladkarnica: String = ""
var KordaA: String = ""
var KordaB: String = ""
var PodImeNaObekt: String = ""
override func viewDidLoad() {
super.viewDidLoad()
let pinLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake((KordaA as NSString).doubleValue,(KordaB as NSString).doubleValue)
let objectAnn = MKPointAnnotation()
objectAnn.coordinate = pinLocation
objectAnn.title = receiveImeNaSladkarnica
objectAnn.subtitle = PodImeNaObekt
self.Mapview.addAnnotation(objectAnn)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func Directions(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/maps?daddr=\((KordaA as NSString).doubleValue),\((KordaB as NSString).doubleValue))")!)
}
#IBAction func MapType(sender: AnyObject) {
if (SegmentControl.selectedSegmentIndex == 0){
Mapview.mapType = MKMapType.Standard
}
if (SegmentControl.selectedSegmentIndex == 1){
Mapview.mapType = MKMapType.Satellite
}
}
#IBAction func LocateMe(sender: AnyObject) {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
Mapview.showsUserLocation = true
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userlocation: CLLocation = locations[0] as CLLocation
manager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion(center: location, span: span)
Mapview.setRegion(region, animated: true )
}
I had the same scenario with an other app.
Within the CLLocation object, there is an instance function:
func distanceFromLocation(location: CLLocation) -> CLLocationDistance
//Get your two locations that you want to calculate the distance from:
let userLocation: CLLocation = ...
let locationToCompare: CLLocation = ...
// Returned value is in meters
let distanceMeters = userLocation.distanceFromLocation(locationToCompare)
// If you want to round it to kilometers
let distanceKilometers = distanceMeters / 1000.00
// Display it in kilometers
let roundedDistanceKilometers = String(Double(round(100 * distanceKilometers) / 100)) + " km"
UPDATED
For your use case
let locations = ... // All locations you want to compare
for location in locations {
let distanceMeters = userLocation.distanceFromLocation(location)
if distanceMeters > 5000 { // Some distance filter
// Don't display this location
} else {
// Display this location
}
}
MY CODE:
IMPROVED
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userlocation:CLLocation = locations[0] as CLLocation
manager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion(center: location, span: span)
Mapview.setRegion(region, animated: true)
let locationStrings = ["42.6977,23.3219","43.6977,24.3219"]
// This array must be an array that contains CLLocation objects
var locations: [CLLocation] = []
// We must retrieve the latitude and longitude from locationStrings array to convert them into CLLocation objects
for locationString in locationStrings {
let location = CLLocation(latitude: <latitude_value>, longitude: <latitude_value>)
locations.append(location)
}
// Then you will be able to enumerate through the array
for location in locations {
let distanceMeters = userLocation.distanceFromLocation(location)
if distanceMeters > 5000 { // Some distance filter
// Don't display this location
} else {
// Display this location
}
}
You can use distanceFromLocation method to get distance
let distance = userlocation.distanceFromLocation(YourPinInMap)
locA = [[CLLocation alloc] initWithLatitude:[[[NSUserDefaults standardUserDefaults]valueForKey:#"startLat"]floatValue] longitude:[[[NSUserDefaults standardUserDefaults]valueForKey:#"startlong"]floatValue]];
locB = [[CLLocation alloc] initWithLatitude:[[[NSUserDefaults standardUserDefaults]valueForKey:#"destLat"]floatValue] longitude:[[[NSUserDefaults standardUserDefaults]valueForKey:#"destLong"]floatValue]];
distance = [locA distanceFromLocation:locB];
where locA and locB are CLLocation type pass the lat long over there

Swift - Return value from locationManager function in class extension

I'm trying to get directions from the users current location to a destination using Google Maps. I want this to be done when the showDirection button is pressed, however I can't figure how to return or pass the users location into the IBAction function from func locationManager(... didUpdateLocation) as the IBAction doesn't use parameters in which I can pass locValue to.
Here is the showDirection button function:
#IBAction func showDirection(sender: AnyObject) {
print("Running showDirection")
let instanceOne = ParseViewController() // Create ParseViewController instance to operate on
print("Created ParseView instance")
let Coord = instanceOne.returnParse()
let latitude = (Coord.lat as NSString)
let longitude = (Coord.long as NSString)
var urlString = "http://maps.google.com/maps?"
urlString += "saddr= // Users location from didUpdateLocation"
urlString += "&daddr= \(latitude as String), \(longitude as String)"
print(urlString)
if let url = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
{
UIApplication.sharedApplication().openURL(url)
}
}
and here is the locationManager function with the locValue:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
let locValue:CLLocationCoordinate2D = (manager.location?.coordinate)!
print("Coordinates = \(locValue.latitude), \(locValue.longitude)")
locationManager.stopUpdatingLocation()
}
}
Any help is greatly appreciated!
You need to create an internal variable in the class to store the location if you want to use it in another function. E.g.
class YourViewController: UIViewController ... {
var lastLocation: CLLocation? = nil
...
}
In didUpdateLocations:
if let location = locations.first {
lastLocation = location
...
}
And now you can access it in func showDirection()

Resources