I have currently this setup and I would love to change from Km to Miles in calculating distance. Here's my current code:
CLLocation *userloc = [[CLLocation alloc] initWithLatitude:locationManager.location.coordinate.latitude longitude:locationManager.location.coordinate.longitude];
CLLocation *loc = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
CLLocationDistance distance2 = [userloc distanceFromLocation:loc]/ 1000;
NSLog(#"%f",distance2);
[distance setText:[NSString stringWithFormat:#"%.2f km", distance2]];
}
It's a simple conversion:
CLLocationDistance distance2 = [userloc distanceFromLocation:loc] * 0.000621371;
NSLog(#"%f",distance2);
[distance setText:[NSString stringWithFormat:#"%.2f mi", distance2]];
Related
I have create a zone on the map and save this coordinate and current zoom level in the database. When we edit this zone and open the map in the mapkit with the same coordinate and zoomlevel region on the map shown is different what we have created.
CLLocationCoordinate2D cd= CLLocationCoordinate2DMake(30.724300, 76.723166);
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(cd, 4640, 4565);
[self.mapView setRegion:viewRegion animated:YES];
Using this function I get the region width and height
-(void) getMapDelta:(CLLocationCoordinate2D) coord
{
MKCoordinateSpan span = self.mapView.region.span;
CLLocationCoordinate2D loc = self.mapView.region.center;
//get latitude in meters
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:(self.mapView.region.center.latitude - span.latitudeDelta * 0.5) longitude:self.mapView.region.center.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:(self.mapView.region.center.latitude + span.latitudeDelta * 0.5) longitude:self.mapView.region.center.longitude];
//get longitude in meters
CLLocation *loc3 = [[CLLocation alloc] initWithLatitude:self.mapView.region.center.latitude longitude:(self.mapView.region.center.longitude - span.longitudeDelta * 0.5)];
CLLocation *loc4 = [[CLLocation alloc] initWithLatitude:self.mapView.region.center.latitude longitude:(self.mapView.region.center.longitude + span.longitudeDelta * 0.5)];
int metersLatitude = [loc1 distanceFromLocation:loc2];
int metersLongitude = [loc3 distanceFromLocation:loc4];
NSLog(#"Delta> %d / %d", metersLongitude,metersLatitude);
NSLog(#"Coor> %f / %f", coord.latitude,coord.longitude);
}
I'm trying to calculate and return the distance between two points and I'm getting a ridiculous number. I've tried both a user-defined haversine method and the distanceFromLocation method and they are both returning 10282657.652... for the distance between lat = 32.60641072/ lon = -85.48713530 and lat = 32.605638 and lon = -85.486890. Are these distances too close?
CLLocation *startLocation = [[CLLocation alloc] initWithLatitude:currentLocation.coordinate.latitude longitude:currentLocation.coordinate.latitude];
CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:_head.lattitude longitude:_head.longitude];
double distance = [startLocation distanceFromLocation:endLocation];
CLLocationCoordinate2D newCoordinate = [startLocation coordinate];
CLLocationCoordinate2D oldCoordinate = [endLocation coordinate];
double distance2 = [self distanceFrom:newCoordinate to:oldCoordinate];
NSNumber *myDoubleNumber = [NSNumber numberWithDouble:distance2];
_charLabel.text = [myDoubleNumber stringValue];
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:lon1];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:lat2 longitude:lon2];
CLLocationDistance distance= [location1 distanceFromLocation:location2]*1.09361;
"distance" will return on meter.
This code worked for me :)
How can i sort the array based on distance from current location and show in tableview .when i use below code for sorting am not getting any proper results ,am getting the array with random distance.can any one guide me for solve this issue
-(void)sort_distance{
// Determine distance between current location and geofence location
[distance_array removeAllObjects];
NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
CLLocation *pinLocation;
CLLocation *userLocation;
for (int i=0; i<[self.geofences count]; i++) {
//dict =[self.geofences objectAtIndex:i];
CLLocationDegrees firstLat = [self.currentLatitude doubleValue];
CLLocationDegrees firstLong = [self.currentLongitude doubleValue];
CLLocationDegrees secondLat = [[[self.geofences objectAtIndex:i] objectForKey:#"lat"] doubleValue];
CLLocationDegrees secondLong = [[[self.geofences objectAtIndex:i] objectForKey:#"lon"] doubleValue];
pinLocation = [[CLLocation alloc]
initWithLatitude:secondLat
longitude:secondLong];
userLocation = [[CLLocation alloc]
initWithLatitude:firstLat
longitude:firstLong];
CLLocationDistance distance = [pinLocation distanceFromLocation:userLocation]/1000;
//current distance is NSNumber
CLLocationDistance kilometers = distance /1000;
// or you can also use this..
distanceString = [[NSString alloc] initWithFormat: #"%.1f Km", kilometers];
NSLog(#"sa: %#", distanceString);
[distance_array addObject:distanceString];
[dict setObject:[NSNumber numberWithDouble:distance] forKey:#"newdistance"];
}
NSLog(#"distance array: %#", distance_array);
// Sorting the Geofence-Location depends on distance from current location
NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:#"newdistance" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sort];
sortedArray = [self.geofences sortedArrayUsingDescriptors:sortDescriptors];
}
My out put is
distance array: (
"0.2 Km",
"0.4 Km",
"0.2 Km",
"0.6 Km",
"0.7 Km",
"1.0 Km",
"0.3 Km"
)
Thanks in Advance,
Chandu.
-(void)sort_distance{
// Determine distance between current location and geofence location
[distance_array removeAllObjects];
NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
CLLocation *pinLocation;
CLLocation *userLocation;
for (int i=0; i<[self.geofences count]; i++) {
//dict =[self.geofences objectAtIndex:i];
CLLocationDegrees firstLat = [self.currentLatitude doubleValue];
CLLocationDegrees firstLong = [self.currentLongitude doubleValue];
CLLocationDegrees secondLat = [[[self.geofences objectAtIndex:i] objectForKey:#"lat"] doubleValue];
CLLocationDegrees secondLong = [[[self.geofences objectAtIndex:i] objectForKey:#"lon"] doubleValue];
pinLocation = [[CLLocation alloc]
initWithLatitude:secondLat
longitude:secondLong];
userLocation = [[CLLocation alloc]
initWithLatitude:firstLat
longitude:firstLong];
CLLocationDistance distance = [pinLocation distanceFromLocation:userLocation]/1000;
//current distance is NSNumber
CLLocationDistance kilometers = distance /1000;
// or you can also use this..
distanceString = [[NSString alloc] initWithFormat: #"%.1f km", kilometers];
NSLog(#"sa: %#", distanceString);
[distance_array addObject:distanceString];
[dict setObject:[NSNumber numberWithDouble:distance] forKey:#"newdistance"];
}
NSLog(#"distance array: %#", distance_array);
// Sorting the Geofence-Location depends on distance from current location
sortedArray = [distance_array sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"%#",sortedArray);
}
CLLocationDistance is double type, while you are saving it as integer type. So you will loose some precision. Instead use `[NSNumber numberWithDouble:].
This will sort in ascending order, for descending order return NSOrderedAscending in place of NSOrderedDescending and vice-versa.
-(CLLocationDistance )distanceOfCurrentPosition:(CLLocation *)userLocation WithPosition:(NSDictionary *)postition{
CLLocationDegrees secondLat = [postition[#"lat"] doubleValue];
CLLocationDegrees secondLong = [postition[#"lon"] doubleValue];
CLLocation *pinLocation = [[CLLocation alloc]
initWithLatitude:secondLat
longitude:secondLong];
CLLocationDistance distance = [pinLocation distanceFromLocation:userLocation]/1000;
CLLocationDistance kilometers = distance /1000;
return kilometers;
}
-(void)sort_distance{
CLLocationDegrees firstLat = [self.currentLatitude doubleValue];
CLLocationDegrees firstLong = [self.currentLongitude doubleValue];
CLLocation *userLocation = [[CLLocation alloc]
initWithLatitude:firstLat
longitude:firstLong];
[_geofences sortUsingComparator:^NSComparisonResult(NSDictionary *position1, NSDictionary *position2) {
CLLocationDistance distanceWithPosition1 = [self distanceOfCurrentPosition:userLocation WithPosition:position1];
CLLocationDistance distanceWithPosition2 = [self distanceOfCurrentPosition:userLocation WithPosition:position2];
if (distanceWithPosition1> distanceWithPosition2) {
return NSOrderedDescending;
}else if(distanceWithPosition2 > distanceWithPosition1){
return NSOrderedAscending;
}else{
return NSOrderedSame;
}
}];
NSLog(#"Order :%#",_geofences);
}
Try these for sort your array
-(NSArray *)sortArray:(NSArray *)arrayForSort forKey:(NSString *)key
{
return [arrayForSort sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if([obj1 isKindOfClass:[NSDictionary class]] && [obj2 isKindOfClass:[NSDictionary class]])
return [[obj1 objectForKey:key] compare:[obj2 objectForKey:key]];
return NSOrderedSame;
}];
}
Just call it your case
self.geofences = [self sortArray:self.geofences forKey:#"newdistance"];
Have a nice day :)
This question already has answers here:
Calculate distance between two place using latitude-longitude in gmap for iPhone [duplicate]
(2 answers)
Closed 8 years ago.
I tried to calculate the distance between two locations but something is wrong because the distance is 0 every time.
float oldLatitude = [gInfo.latitude floatValue];
float oldLongitude = [gInfo.longitude floatValue];
CLLocation *oldLocation = [[CLLocation alloc] initWithLatitude:oldLatitude longitude:oldLongitude];
CLLocation *newLocation = [[CLLocation alloc] initWithLatitude:newLatitude longitude:newLongitude];
if (newLatitude == 0 && newLongitude == 0) {
[self showAlarm2];
return;
}
float distance = [newLocation distanceFromLocation:oldLocation];
// distance 0 ????????
int result = (int)roundf(distance );
if (result < 0) {
result = -result;
}
// long result = (long)distance;
NSLog(gInfo.name );
NSLog(#"Distance i meters: %i", result);
//**************** filter group by check distance *************
if (result <= 10) {
[viewArray addObject:gInfo];
}
Use this
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
latitude = coordinate.latitude;
longitude = coordinate.longitude;
MKCoordinateRegion myRegion;
MKCoordinateSpan mySpan;
mySpan.latitudeDelta = 1.0f;
mySpan.longitudeDelta = 1.0f;
myRegion.center = coordinate;
myRegion.span = mySpan;
//-----------------------------------------------
NSDictionary *dict = (NSDictionary*)[arrayJsonData objectAtIndex:indexPath.row];
CLLocation *locA = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:[[dict1 valueForKey:#"Latitude"] doubleValue] longitude:[[dict1 valueForKey:#"Longitude"] doubleValue]];
CLLocationDistance distance = [locA distanceFromLocation:locB];
double distanceInMiles = (distance/CONVERSION_TO_MILES);
// CONVERSION_TO_MILES 1609.344
I am trying to find the distance in miles using the latitude and longitude. I have the following method:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if(!newLocation) return;
if ((oldLocation.coordinate.latitude != newLocation.coordinate.latitude) &&
(oldLocation.coordinate.longitude != newLocation.coordinate.longitude))
{
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:oldLocation.coordinate.latitude longitude:oldLocation.coordinate.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.latitude];
CLLocationDistance distance = ([loc2 distanceFromLocation:loc1]) * 0.000621371192;
//distance = distance;
NSLog(#"Total Distance %f in miles",distance);
}
}
For some reason it prints out something like 5678.32 miles. The location is pretty much stationary and not moving at all.
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.(!!!!!)latitude longitude:newLocation.coordinate.(!!!!!)latitude];
You are initializing loc2 with the latitude of the new location for both the longitude and the latitude:
This line:
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.latitude];
Should say:
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
Hope it helps!