views:

977

answers:

3

Hello!

I have a problem what I suppose is rather trivial... I have coded an app using the mapkit and have done the development on my Mac using the simulator which has no GPS. Therefore did I hard code the coordinates to simulate a user position. Today as I tried my app on my iPhone for the first time I thought I only had to change my code a bit in order to read the coordinates from the GPS and to get the information about the users position. But it did not work that easy. Does anyone have an idea how to solve this? I need the user longitude and latitude to calculate the distance to another position and I thought I could do something like this...?

CLLocationManager *clm = [[CLLocationManager alloc]init];
[clm.delegate self]; [clm startUpdatingLocation];

userLocationFromGPS = clm.location.coordinate;
//the userLocationFromGPS is a CLLocationCoordinate2D userLocationFromGPS object

user = [[Annotations alloc]initWithCoordinate:userLocationFromGPS];
[user setTheTitle:@"You are here!"];

userLocationPlain =
[[CLLocation alloc]initWithLatitude:userLocationFromGPS.latitude longitude:userLocationFromGPS.longitude];

I need the coordinates but cant figure out how to get them...any ideas? Thanks in advance!

+2  A: 

CLLocationManager reports location asynchronisly, so you would need to provide a delegate.
Consider going over LocateMe code sample. Also, you should hard-code coordinates in the simulator. The simulator would use the Apple headquarters coordinates.

Here is some refactoring for the code you provided (I didn't run it): Consider doing the following:


   CLLocationManager *clm = [[CLLocationManager alloc] init];
   clm.delegate = self;
   [clm startUpdatingLocation];

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{

   Annotations *user = [[Annotations alloc] initWithCoordinate:newLocation];
   [user setTheTitle:@"You are here!"];

   CLLocation *userLocationPlain = 
     [[CLLocation alloc] initWithLatitude:newLocation.latitude
                         longitude:newLocation.longitude];

   // At some point you should call [manager stopUpdatingLocation]
   // and release it
}
notnoop
A: 

As this says, you might need to first import the location framework.

mcandre
A: 

Thank you both for answering!

msaeed: Your code is looking good. I have defined a delegate but forgot to implement the method as you do in you example. I will try it out! Thanks!

mcandre: Yes I added the framework and I use the functionalities in it in other methods in my app, when reading and handling position from a KML.

/MACloop

Great! In the future, consider leaving comments instead of adding an "answer".
notnoop
Ah - yes! I didnt know about that feature ;-)Thanks again!