0

I am using this function to get the distance from one CLLocation to another

here venue.lat is NSNumber

GeoAddress *address = [[GeoAddress new] init];

CLLocationCoordinate2D coord;
coord.longitude = (CLLocationDegrees)[venue.lat doubleValue];
coord.latitude = (CLLocationDegrees)[venue.lng doubleValue];

address.latlng = [[CLLocation alloc] initWithLatitude:coord.latitude longitude: coord.longitude];

if (curUserLocation.coordinate.latitude){
    address.distance = [address.latlng distanceFromLocation:curUserLocation];
    NSLog(@" DISTANCE %f", address.distance);
    NSLog(@" LOC1 %f lat %f lng", address.latlng.coordinate.latitude, address.latlng.coordinate.longitude);
    NSLog(@" ME %f lat %f lng", curUserLocation.coordinate.latitude, curUserLocation.coordinate.longitude);
}

This is Geoaddress:

//  GeoAddress.h
@interface GeoAddress : NSObject
{        
    CLLocation * latlng;
   CLLocationDistance  distance;
}
@property  CLLocationDistance  distance;
@property (nonatomic, retain)  CLLocation * latlng;

//  GeoAddress.m
#import "GeoAddress.h"

@implementation GeoAddress
@synthesize distance;
@synthesize  latlng;

This is the log:

DISTANCE 15106456.105786
LOC1 -73.986357 lat 40.702645 lng
ME 40.702082 lat -73.984775 lng

The numbers are completely off actual distance is ~0.17 km

What am I doing wrong??

Stpn
  • 6,202
  • 7
  • 47
  • 94

3 Answers3

5

You have lines that say:

coord.longitude = (CLLocationDegrees)[venue.lat doubleValue];
coord.latitude = (CLLocationDegrees)[venue.lng doubleValue];

Obviously that should be:

coord.longitude = (CLLocationDegrees)[venue.lng doubleValue];
coord.latitude = (CLLocationDegrees)[venue.lat doubleValue];
Rob
  • 415,655
  • 72
  • 787
  • 1,044
1

Where you set coord from venue, the latitude and longitude are being assigned backwards.

This gives you the unexpected distance.

1

Look at your output:

LOC1 -73.986357 lat 40.702645 lng
ME 40.702082 lat -73.984775 lng

You exchanged lat and long in ME

AlexWien
  • 28,470
  • 6
  • 53
  • 83