Core Location didEnterRegion method can not work with more than one regions - ios

I'm working on a project about location based reminder. I have used CoreLocation's didEnterRegion method. so when I set a location for entering region, I can take a notification but whenever I want to set another location for entry with didEnterRegion method it only see first one. The method cannot be called for second location. Could you help me?
Here is my code:
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController,CLLocationManagerDelegate {
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let latitude1: CLLocationDegrees = 78.98
let longitude1: CLLocationDegrees = 90.09
let center1: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude1, longitude1)
let radius1: CLLocationDistance = CLLocationDistance(100.0)
let identifier1: String = "Notre Dame"
let currRegion1 = CLCircularRegion(center: center1, radius: radius1, identifier: identifier1)
let latitude: CLLocationDegrees = 20.2020
let longitude: CLLocationDegrees = 2.2945
let center: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let radius: CLLocationDistance = CLLocationDistance(100.0)
let identifier: String = "Notre Dame"
let currRegion = CLCircularRegion(center: center, radius: radius, identifier: identifier)
locationManager.distanceFilter = 10
locationManager.desiredAccuracy = kCLLocationAccuracyBest
currRegion1.notifyOnEntry = true
currRegion.notifyOnEntry = true
locationManager.delegate=self
locationManager.requestAlwaysAuthorization()
locationManager.startMonitoring(for: currRegion1)
locationManager.startMonitoring(for: currRegion)
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if region is CLCircularRegion {
handleEvent(forRegion: region)
}
}
func handleEvent(forRegion region: CLRegion!) {
print("Geofence triggered!")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

The official document:
You must call this method once for each region you want to monitor. If
an existing region with the same identifier is already being monitored
by the app, the old region is replaced by the new one.
So make the different identifier:
//...
let identifier1: String = "Notre Dame1"
//...
let identifier: String = "Notre Dame2"
//...

Related

Why userLocation returns (-180.0,-180.0) coordinates on Mapbox?

I use Mapbox with Swift 4 and I have a problem when I want to display the user location. I don't understand why the user location is not set as it should be.
I would get the user location coordinates in the viewDidLoad() method. To do so, I have set MGLMapViewDelegate and CLLocationManagerDelegate in my ViewController declaration. Then, in my viewDidLoad() I have:
// Mapview configuration
let mapView = MGLMapView(frame: self.mapView.bounds)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.showsUserLocation = true
mapView.setUserTrackingMode(.follow, animated: true)
mapView.delegate = self
self.mapView.addSubview(mapView)
// User location
print("User location:")
print(mapView.userLocation!.coordinate)
But I get this:
CLLocationCoordinate2D(latitude: -180.0, longitude: -180.0)
I think it is because the location is not set when the view loads, but I need to get values in viewDidLoad().
What should I do, and why the line mapView.userLocation!.coordinate doesn't work?
EDIT
In fact, I want to use MapboxDirections to display on the map a line between the user location and a fixed point. To do it, I use this code (see the first comment):
let waypoints = [
// HERE I would use the user location coordinates for my first Waypoint
Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.9131752, longitude: -77.0324047), name: "Mapbox"),
Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), name: "White House"),
]
let options = RouteOptions(waypoints: waypoints, profileIdentifier: .automobileAvoidingTraffic)
options.includesSteps = true
_ = directions.calculate(options) { (waypoints, routes, error) in
guard error == nil else {
print("Error calculating directions: \(error!)")
return
}
if let route = routes?.first, let leg = route.legs.first {
print("Route via \(leg):")
let distanceFormatter = LengthFormatter()
let formattedDistance = distanceFormatter.string(fromMeters: route.distance)
let travelTimeFormatter = DateComponentsFormatter()
travelTimeFormatter.unitsStyle = .short
let formattedTravelTime = travelTimeFormatter.string(from: route.expectedTravelTime)
print("Distance: \(formattedDistance); ETA: \(formattedTravelTime!)")
if route.coordinateCount > 0 {
// Convert the route’s coordinates into a polyline.
var routeCoordinates = route.coordinates!
let routeLine = MGLPolyline(coordinates: &routeCoordinates, count: route.coordinateCount)
// Add the polyline to the map and fit the viewport to the polyline.
mapView.addAnnotation(routeLine)
mapView.setVisibleCoordinates(&routeCoordinates, count: route.coordinateCount, edgePadding: .zero, animated: true)
}
}
}
Larme is correct: the user's location typically isn't available yet in -viewDidLoad. Use the -mapView:didUpdateUserLocation: delegate method to be notified when the user's location becomes available and when it updates.
If you need the user’s location before a map is shown, consider running your own CLLocationManager.
-180, -180 is the kCLLocationCoordinate2DInvalid constant from Core Location. You should typically check if CLLocationCoordinate2DIsValid() before trying to display CLLocationCoordinate2D on a map.
Sergey Kargopolov has a great example of how to obtain the user location using CLLocationManager and CLLocationManagerDelegate. Here is his code:
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
determineMyCurrentLocation()
}
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
// Call stopUpdatingLocation() to stop listening for location updates,
// other wise this function will be called every time when user location changes.
// manager.stopUpdatingLocation()
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
}

iOS & Swift: display distance from current location?

I have scoured the interwebs and stackoverflow, and I can't find a solution to my problem.
I am attempting to:
Get a user's current location (lat & long)
Calculate the distance between a user's current location and another location (lat & long) that I set internally
Return the distance in a list view
So far, I can accomplish this if I manually set my current location, but I need to to update.
I have had success returning my current location (I set it as Apple headquarters in the Simulator) in the log, but no success in the actual app or simulator.
Here's what I have:
import UIKit
import CoreLocation
import MapKit
class ViewController: UITableViewController, CLLocationManagerDelegate, MKMapViewDelegate {
override func prefersStatusBarHidden() -> Bool {
return true
}
var shops = [coffeeShop]()
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
loadShops()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
func loadShops() {
let currentLocation = CLLocation()
let currentLat = currentLocation.coordinate.latitude
let currentLong = currentLocation.coordinate.longitude
var myLocation = CLLocation(latitude: currentLat, longitude: currentLong)
let shopLocation1 = CLLocation(latitude: 39.7886939, longitude: -86.1547275)
let distance1 = myLocation.distanceFromLocation(shopLocation1) / 1000
let shop1 = coffeeShop(location: distance1)!
}
In addition, I have everything set in the info.plist and all of that good stuff.
HOW DO I MAKE THIS WORK!? * weeps softly *
Thanks in advance for all of your help!
I was able to use the following code to achieve what I needed. Sometimes you just gotta put it out there in the universe for the universe to respond on its own. Thanks everyone for the help!
let currentLat = self.locationManager.location!.coordinate.latitude
let currentLong = self.locationManager.location!.coordinate.longitude

didEnterRegion, didExitRegion not being called

I've been experimenting with region monitoring in order to show an alert or a local notification when the user is within the set region. As a first step, I added a print line to see if it works on the debug area. However, while the other lines are being printed, I'm not getting anything for didEnterRegion and didExitRegion.
I am simulating the location to be in/outside of the given region but I am having no luck. It will be great if someone could look at the code below and see what I've missed. Thank you.
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var manager = CLLocationManager?()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager = CLLocationManager()
let latitude: CLLocationDegrees = 48.858400
let longitude: CLLocationDegrees = 2.294500
let center: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let radius: CLLocationDistance = CLLocationDistance(100.0)
let identifier: String = "Notre Dame"
let currRegion = CLCircularRegion(center: center, radius: radius, identifier: identifier)
manager?.distanceFilter = 10
manager?.desiredAccuracy = kCLLocationAccuracyBest
currRegion.notifyOnEntry = true
currRegion.notifyOnExit = true
manager?.requestWhenInUseAuthorization()
manager?.delegate = self
manager?.pausesLocationUpdatesAutomatically = true
manager?.startMonitoringForRegion(currRegion)
manager?.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didStartMonitoringForRegion region: CLRegion) {
print("The monitored regions are: \(manager.monitoredRegions)")
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
NSLog("Entered")
}
func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
NSLog("Exited")
}
}
You can make it work by changing
manager?.requestWhenInUseAuthorization()
to
manager?.requestAlwaysAuthorization()
then add to your info.plist file this key
NSLocationAlwaysUsageDescription with value "This is for testing purpose" or whatever text you want this is what will appear to user requesting to use location

Current Location in Google Maps with swift

I'm trying to display the user's current location on a google map but in the case below, the map doesn't even get displayed. What should I change to fix this?
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//user location stuff
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error" + error.description)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation = locations.last
let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)
let camera = GMSCameraPosition.cameraWithLatitude(userLocation!.coordinate.latitude,
longitude: userLocation!.coordinate.longitude, zoom: 8)
let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
mapView.myLocationEnabled = true
self.view = mapView
let marker = GMSMarker()
marker.position = center
marker.title = "Current Location"
marker.snippet = "XXX"
marker.map = mapView
locationManager.stopUpdatingLocation()
}
You can try this bellow code its working fine
import UIKit
import GoogleMaps
import GooglePlaces
class SearchMapsViewController: UIViewController,
UINavigationBarDelegate, GMSAutocompleteFetcherDelegate,
LocateOnTheMap, UISearchBarDelegate, CLLocationManagerDelegate
{
#IBOutlet var googleMapsContainerView: UIView!
var searchResultController: SearchResultsController!
var resultsArray = [String]()
var googleMapsView:GMSMapView!
var gmsFetcher: GMSAutocompleteFetcher!
var locationManager = CLLocationManager()
override func viewDidAppear(animated: Bool) {
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
self.googleMapsView = GMSMapView (frame: self.googleMapsContainerView.frame)
self.googleMapsView.settings.compassButton = true
self.googleMapsView.myLocationEnabled = true
self.googleMapsView.settings.myLocationButton = true
self.view.addSubview(self.googleMapsView)
searchResultController = SearchResultsController()
searchResultController.delegate = self
gmsFetcher = GMSAutocompleteFetcher()
gmsFetcher.delegate = self
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Error" + error.description)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let userLocation = locations.last
let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)
let camera = GMSCameraPosition.cameraWithLatitude(userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude, zoom: 15);
self.googleMapsView.camera = camera
self.googleMapsView.myLocationEnabled = true
let marker = GMSMarker(position: center)
print("Latitude :- \(userLocation!.coordinate.latitude)")
print("Longitude :-\(userLocation!.coordinate.longitude)")
marker.map = self.googleMapsView
marker.title = "Current Location"
locationManager.stopUpdatingLocation()
}
do requier setting on infoPlist and then try this
#IBOutlet weak var your "name of view which show map": GMSMapView!
override func viewDidLoad(){
super.viewDidLoad()
placesClient = GMSPlacesClient.shared()
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.distanceFilter = 500
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
mapView.settings.myLocationButton = true
mapView.settings.zoomGestures = true
mapView.animate(toViewingAngle: 45)
mapView.delegate = self }
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last // find your device location
mapView.camera = GMSCameraPosition.camera(withTarget: newLocation!.coordinate, zoom: 14.0) // show your device location on map
mapView.settings.myLocationButton = true // show current location button
var lat = (newLocation?.coordinate.latitude)! // get current location latitude
var long = (newLocation?.coordinate.longitude)! //get current location longitude
}
The problem is that you are setting the mapView's frame to CGRectZero. This causes the map to have zero height and zero width, no wonder it does not show!
Try setting it to CGRectMake(0,0,200,200) for example, this will give you a map at the left top of the screen with a size of 200 x 200.
I have never used Swift before, so the syntax might be a little different for CGRectMake()
It seems that your creation of the map isn't in your viewDidLoad function. You may want to try moving that there and see what happens.
Add the appropriate properties into the info.plist.
You should put make sure you have the NS properties of locationalwaysusagedescription and wheninuseusagedescription in the information properties list. This allows for the permissions of the current location to be asked.
import UIKit
import GoogleMaps
import GooglePlaces
import CoreLocation
class MapsViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
var mapView = GMSMapView()
var locationManager = CLLocationManager()
let marker = GMSMarker()
override func viewDidLoad(){
super.viewDidLoad()
mapView.frame = self.view.bounds
self.view.addSubview(mapView)
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 10
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
mapView.settings.myLocationButton = true
mapView.settings.zoomGestures = true
mapView.animate(toViewingAngle: 45)
mapView.delegate = self
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last // find your device location
mapView.camera = GMSCameraPosition.camera(withTarget: newLocation!.coordinate, zoom: 14.0) // show your device location on map
mapView.settings.myLocationButton = true // show current location button
let lat = (newLocation?.coordinate.latitude)! // get current location latitude
let long = (newLocation?.coordinate.longitude)! //get current location longitude
marker.position = CLLocationCoordinate2DMake(lat,long)
marker.map = mapView
print("Current Lat Long - " ,lat, long )
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
mapView.clear()
DispatchQueue.main.async {
let position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
self.marker.position = position
self.marker.map = mapView
self.marker.icon = UIImage(named: "default_marker")
print("New Marker Lat Long - ",coordinate.latitude, coordinate.longitude)
}
}
}

Why does this function keep looping?

func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
MapOutlet.setRegion(coordinateRegion, animated: true)
}
This function above within my view controller below continues to run although I never coded any loop in, can someone help spot the incorrect logic. Here is the rest of the view controller
import UIKit
import MapKit
import CoreLocation
class ViewControllerPublic: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
let initialLocation = CLLocation(latitude: 3.632488, longitude: -117.898886)
override func viewDidLoad() {
super.viewDidLoad()
centerMapOnLocation(initialLocation)
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
let currentLocation = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude)
centerMapOnLocation(currentLocation)
}
let regionRadius: CLLocationDistance = 2300
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
MapOutlet.setRegion(coordinateRegion, animated: true)
}
#IBOutlet weak var MapOutlet: MKMapView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You never invalidate the CLLocation manager so as #Ashish Kakkad said, whenever you get even the slightest location change your function is getting called again. If you don't want this behavior, then after you get a location in didUpdateLocations you need to do locationManager.stopUpdatingLocation(). Or, if you do want your app to update the map every time the location changes, you may want to think about changing your desired location accuracy.

Resources