- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// If it's a relatively recent event, turn off updates to save power
NSLog(#"%# locations",locations);
float Lat = _locationManager.location.coordinate.latitude;
float Long = _locationManager.location.coordinate.longitude;
NSLog(#"Lat : %f Long : %f",Lat,Long);
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(28.52171,77.2015457);
NSLog(#"center check %#",center);
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:center
radius:500
identifier:#"new region"];
BOOL doesItContainMyPoint = [region containsCoordinate:CLLocationCoordinate2DMake(Lat,Long)];
NSLog(#"success %hhd", doesItContainMyPoint);
}
the issue is ,here i m providing a static region for which i m checking (center)
but the requirement is, this region will take the lat n long of the riders and riders can vary in number
i hv all lat n long in an array of dictionary. First the driver will pick the first rider in the list and at that time i need the region of rider 1 location.
I m not getting any idea how to achieve this
if i do like this
for (NsMutableDictionary * dict in goersList)
{
rider_id=[dict valueForKey:#"trip_id"];
lat=[dict valueForKey:#"origin_lat"];
longi=[dict valueForKey:#"origin_long"];
}
then how will it know that the first region is to be monitored and after existing from that range i hv to check for second location
You can create dynamically regions and add them to monitoring.
for (NSDictionary *dict in [result valueForKey:#"Geofences"])
{
NSLog(#"%#",dict);
CLLocationCoordinate2D locationCoordinate=CLLocationCoordinate2DMake([[dict valueForKey:#"cLatitude"]doubleValue], [[dict valueForKey:#"cLongitude"]doubleValue]);
CLCircularRegion *circularRegion=[[CLCircularRegion alloc]initWithCenter:locationCoordinate radius:[[dict valueForKey:#"Radius"]doubleValue] identifier:[dict valueForKey:#"Name"]];
circularRegion.notifyOnEntry=YES;
circularRegion.notifyOnExit=YES;
[[AppDelegate sharedDelegate].locationManager startMonitoringForRegion:circularRegion];
NSLog(#"%#",[[[AppDelegate sharedDelegate] locationManager].monitoredRegions description]);
}
Here there are several regions are added to monitoring. You can add single at a time. i.e on selection of tableview.
And remove others using below code
for (CLRegion *monitored in [[AppDelegate sharedDelegate].locationManager monitoredRegions])
{
[[AppDelegate sharedDelegate].locationManager stopMonitoringForRegion:monitored];
}
Related
I have two locations one is the driver and other is the rider.I have lat n long available for both.I want to hit an api when the driver enters in the geofence area of the riders location.
i went through QKGeofenceManager demo project:
using this i can provide lat n long and the radius to find geofence.
But the issue is do i have to update driver location every time in background and what condition should be applied so the the callback is made when the driver enters the geofence area of rider.If the ap is in background how will it handle everything.
Do i have to make any changes in appdelegate
- (NSArray *)geofencesForGeofenceManager:(QKGeofenceManager *)geofenceManager
{
NSArray *fetchedObjects = [self.fetchedResultsController fetchedObjects];
NSMutableArray *geofences = [NSMutableArray arrayWithCapacity:[fetchedObjects count]];
for (NSManagedObject *object in fetchedObjects) {
NSString *identifier = [object valueForKey:#"identifier"];
CLLocationDegrees lat = [[object valueForKey:#"lat"] doubleValue];
CLLocationDegrees lon = [[object valueForKey:#"lon"] doubleValue];
CLLocationDistance radius = [[object valueForKey:#"radius"] doubleValue];
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(lat, lon);
CLCircularRegion *geofence = [[CLCircularRegion alloc] initWithCenter:center radius:radius identifier:identifier];
[geofences addObject:geofence];
}
return geofences;
}
I found an alternative to achieve this task.
As my delegate method of Didenterlocation was not called,i applied another approach.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// If it's a relatively recent event, turn off updates to save power
NSLog(#"%# locations",locations);
float Lat = _locationManager.location.coordinate.latitude;
float Long = _locationManager.location.coordinate.longitude;
NSLog(#"Lat : %f Long : %f",Lat,Long);
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(28.58171,77.2915457);
NSLog(#"center check %#",center);
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:center
radius:500
identifier:#"new region"];
BOOL doesItContainMyPoint = [region containsCoordinate:CLLocationCoordinate2DMake(Lat,Long)];
NSLog(#"success %hhd", doesItContainMyPoint);
}
by keeping track of the current location,whenever the current location coordinates enter into the coordinates of the center region,you can fire a notification that the user has entered this particular region.
I'm working on an application for the iPhone and I'm keeping track of the users current location. When the didupdateLocations delegate method actually executes i would like to test if the location in the NSArray is in a predefined array the contains other locations, this array mind you could grow over time.
I'm running a for loop within this method to test against my own array of locations but i would like to move that to a separate thread. So in case my own array with multiple locations grows to a large number the for loop does not freeze my UI.
I have tried it like this but I'm getting undesirable results. I understand that the location tracking definitely happens in a separate thread. However those didupdateLocations execute on a separate thread. The Apple doc's are not very clear on the matter. My end goal again is to compare against my array and not lock the UI.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)thisLocation {
dispatch_queue_t queue= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// get the last object in the array of locations
CLLocation* location = [thisLocation lastObject];
dispatch_async(queue, ^{
[self checkmyArray:location];
});
}
-(void)checkmyArray:(CLLocation *)workingLocation{
NSLog(#"SoundTheAlarm");
int alarm_on_c = 0;
NSUInteger tmp_count = [theData.LocationsObjectArray count];
BOOL alarm;
NSMutableDictionary * tempObject;
CLLocationDistance distance = 0.0;
for (int i = 0; i < tmp_count; i++) {
tempObject= [theData.LocationsObjectArray objectAtIndex:i];
thisLoc = [[tempObject objectForKey:#"onoff"] isEqual:#YES];
if (thisLoc) {
//check if we are near that location
double lat = [[tempObject objectForKey:#"latitude"] doubleValue];
double lon = [[tempObject objectForKey:#"longitude"] doubleValue];
// goal = [[CLLocation alloc] initWithLatitude:40.097771 longitude:-74.941399];
goal = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
// check the destination between current location and goal location - in meters
distance = [goal distanceFromLocation:workingLocation];
NSLog(#"distance %f\n", distance);
}
// if distance from goal is less than 350 meters
if (distance <= 350){
[self scheduleNotification:[tempObject objectForKey:#"name"]];
// turn off tracking for this location
[tempObject setObject:#NO forKey:#"onoff"];
[theData.LocationsObjectArray replaceObjectAtIndex:i withObject:tempObject];
NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0];
ExtendedSavedCellTableViewCell *cell = (ExtendedSavedCellTableViewCell *)[self.tableView cellForRowAtIndexPath:path];
cell.switchView.on = NO;
// save the update to the switch to the database as well
NSString *lat = [tempObject objectForKey:#"latitude"];
/*check to determine if the uiswitch is turned off or on.*/
[self fetchedResultsController:#NO lat:lat index:path];
[self displayAlertViewForAlarm:[tempObject objectForKey:#"name"]];
}
-(void)displayAlertViewForAlarm:(NSString *)nameOfLocation{
dispatch_async(dispatch_get_main_queue(), ^(void) {
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:#"Destination reached"
message:nameOfLocation
delegate:self
cancelButtonTitle:#"Go Away"
otherButtonTitles:#"Notify", nil];
[myAlert show];
});
}
It's generally a bad idea to use threads in iOS if you can at all avoid it. In your case, I'd implement the function which does the looping to automatically pop out of the loop after too many iterations and then schedule the next chunk of iterating to happen in another pass through the event loop. In other words, something like this:
- (void) checkLocationsStartingAt:(NSNumber)start
{
NSInteger s = (start) ? [start intValue] : 0;
for (i = s; i < list.length; i++) {
if (i > TOO_MANY) {
[self performSelector:#selector(checkLocationsStartingAt:)
withObject:#(i)
afterDelay:0.001];
return;
} else {
// check element at i
}
}
}
see: NSObject Reference
You are checking one location against an array of other locations.
You display an alert for time you are closer than 350m from a location.
You could be within 350m of many items in the list.
You have no code prevent multiple alerts.
So you will sometimes have many alerts.
You have a couple options. One will probably suit your needs better than the others. Possibly one I didn't list.
You could re-use a single UIAlertView instance and check the
visible property on it. If it's already visible, do nothing.
You could break out of the loop once you get a single "hit" on being
<350m.
You could stick in a BOOL which records if you've shown the alert and
check the BOOL every time before you show the alert again.
I have just completed compass app which will show distance between 2 coordinates.
Here is working code :
....
// created a timer to call locationUpdate method : 5sec
[NSTimer scheduledTimerWithTimeInterval:5 target: self selector: #selector(locationUpdate) userInfo: nil repeats: YES];
....
-(void)locationUpdate {
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLoc
fromLocation:(CLLocation *)oldLoc
{
//To get the current location Latitude & Longitude.
float latitude = locationManager.location.coordinate.latitude;
float longitude = locationManager.location.coordinate.longitude;
startPoint = [[CLLocation alloc] initWithLatitude: latitude longitude: longitude ]; //Current Latitude and Longitude
endPoint = [[CLLocation alloc] initWithLatitude: 12.923670 longitude: 77.573496]; //Target Latitude and Longitude -----------------------------------> Need to come from database.
//To get the distance from the 2 coordinates in feet
CLLocationDistance distInMeter = [startPoint distanceFromLocation:endPoint];
//Lable veiw to update remaining distance.
if(distInMeter > 999.000f) {
self.labelLongLat.text = [NSString stringWithFormat: #"Remainig distance %.2f KM with Lat : %lf LAN %lf", distInMeter / 1000, latitude, longitude ];
}else
self.labelLongLat.text = [NSString stringWithFormat: #"Remainig distance %.2f M Lat : %lf LAN %lf" , distInMeter, latitude,longitude ];
}
My problem is while updating location for each 5sec, the coordinates varies a lot. That will result in Remaining distance calculation. Which is highly unstable!! How can I fix this?
Thanks in Advance,
The delegate method you are using is deprecated. You should use locationManager:didUpdateLocations:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currentLocation = [locations lastObject];
endPoint = [[CLLocation alloc] initWithLatitude: 12.923670 longitude: 77.573496]; //Target Latitude and Longitude -----------------------------------> Need to come from database.
//To get the distance from the 2 coordinates in meters
CLLocationDistance distInMeter = [currentLocation distanceFromLocation:endPoint];
//Label view to update remaining distance.
if(distInMeter > 999 ) {
self.labelLongLat.text = [NSString stringWithFormat: #"Remaining distance %.2f Km with Lat : %lf LAN %lf", distInMeter / 1000, currentLocation.coordinate.latitude, currentLocation.coordinate.longitude ];
} else {
self.labelLongLat.text = [NSString stringWithFormat: #"Remaining distance %.2f m Lat : %lf LAN %lf" , distInMeter, currentLocation.coordinate.latitude, currentLocation.coordinate.longitude ];
}
}
The accuracy of your location can be affected by signal quality (tall buildings, indoor location etc). You can examine the horizontalAccuracy property of your location to see how accurate the position is. If the accuracy is low then you can defer updating your label. Beware that you may never get an accurate fix.
One strategy is to wait for an accuracy <20m or after 5 updates -
#property (nonatomic) NSInteger locationUpdates;
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
self.locationUpdates++;
CLLocation *currentLocation = [locations lastObject];
if (currentLocation.horizontalAccuracy < 20.0 || self.locationUpdates>5) {
endPoint = [[CLLocation alloc] initWithLatitude: 12.923670 longitude: 77.573496]; //Target Latitude and Longitude -----------------------------------> Need to come from database.
//To get the distance from the 2 coordinates in meters
CLLocationDistance distInMeter = [currentLocation distanceFromLocation:endPoint];
//Label view to update remaining distance.
if(distInMeter > 999 ) {
self.labelLongLat.text = [NSString stringWithFormat: #"Remaining distance %.2f Km with Lat : %lf LAN %lf", distInMeter / 1000, currentLocation.coordinate.latitude, currentLocation.coordinate.longitude ];
} else {
self.labelLongLat.text = [NSString stringWithFormat: #"Remaining distance %.2f m Lat : %lf LAN %lf" , distInMeter, currentLocation.coordinate.latitude, currentLocation.coordinate.longitude ];
}
}
}
In my iOS app I've to track the distance from a a start point to my current location. I implemented this code:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *currentLocation = [locations lastObject];
CLLocation *startLocation = [locations firstObject];
[coordArray addObject:currentLocation];
float speed = currentLocation.speed * 3.6;
if (speed > 0) {
self.labelSpeed.text = [NSString stringWithFormat:#"%.2f Km/h", speed];
[speedArray addObject:[NSNumber numberWithFloat:speed]];
}
CLLocationDistance distance = [startLocation distanceFromLocation:currentLocation];
}
But when I try to use the app it doesn't get a distance. I need the distance to show it in a label and with distance I will calculate the number of steps by using this equation:
steps = distance / length of human step
I know that it's not accurate, but I can't use accelerometer, because it doesn't work while the display of the iPhone is not active. A person suggested me this solution. Why my code doesn't give me a distance?
The callback
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
does give you at least one location, and locations array hold sonly multiple objects if the location update was deferred before. To get the walking/driving distance, you have to store the initial location in a class variable or property. Then, when you want to calculate a distance, do as in your code above, but with the class variable that holds the initial location.
Check below code for getting distance:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
if ([coordArray count]>0) {
CLLocation *currentLocation = manager.location;
CLLocation *startLocation = [coordArray objectAtIndex:0];
[coordArray addObject:currentLocation];
float speed = currentLocation.speed * 3.6;
if (speed > 0) {
NSLog(#"\n speed:%#",[NSString stringWithFormat:#"%.2f Km/h", speed]);
}
CLLocationDistance distance = [startLocation distanceFromLocation:currentLocation];
if (distance>0) {
NSLog(#"Distance:%#",[NSString stringWithFormat:#"%lf meters",distance]);
}
}
else{
[coordArray addObject:manager.location];
}
}
)
i have an mutable array of restaurantObjects serialized form json data, if current object is named restaurantDetail i can acces corrdinates like this
float x = [[restaurantDetail.coordinates objectAtIndex:0] floatValue];
float y = [[restaurantDetail.coordinates objectAtIndex:1] floatValue];
so i would like to extract restaurants which are close to users location and store them to array
and if user changes location array should get updated too
i would really apprichiate help because i am completely lost here
i have tried this form Muthub Ram
- (void) checkIfInRegion{
Restaurant * currentRestaurant;
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
for(int i=0;i<[restaurantsArray count];i++){
currentRestaurant = [restaurantsArray objectAtIndex:i];
//NSLog(#"%#",currentRestaurant.coordinates);
CLLocation * currentRestLoc = [[CLLocation alloc] initWithCoordinate:CLLocationCoordinate2DMake([[currentRestaurant.coordinates objectAtIndex:0] floatValue], [[currentRestaurant.coordinates objectAtIndex:1] floatValue])
altitude:0
horizontalAccuracy:0
verticalAccuracy:0
timestamp:[NSDate date]];
NSLog(#"%#",currentRestLoc);
if([locationManager.location distanceFromLocation:currentRestLoc] <100)
{
//if less than 100meters
//then add object in this array
[near_by_user addObject:[restaurantsArray objectAtIndex:i]];
}
}
NSLog(#"%#",locationManager.location);
NSLog(#"restaurants near%#",near_by_user);
[locationManager stopUpdatingLocation];
}
i get all coordinates form location but i dont get any objects in near_by_user array ( it remains empty)
http://pastebin.com/fc8q69Le here is log, last set of coordinates is my location same as one of restaurants
for(i=0;i<[array_res count];i++){
if([clloc distanceFromLocation:[array_res objectatindex:i]<100])
{
//if less than 100meters
//then add object in this array
[near_by_user addobject:[array_res objectatindex:i];
}
}
please add this code.if you have any clarification update here