Converting CLLocationCoordinate2D into PFGeoPoint? - ios

I get user's current location with CLLocationCoordinate2D then would like to use it for Parse's nearGeoPoint.
I know I can just simply use geoPointForCurrentLocationInBackground but I'd rather retrieve with CLLocationCoordinate2D instead.

You can use the geoPointWithLatitude:longitude: initializer of the PFGeoPoint class. Give it the latitude and longitude values of your CLLocationCoordinate2D, and you'll have your PFGeoPoint.
e.g.
PFGeoPoint *geoPoint = [PFGeoPoint geoPointWithLatitude:coordinate.latitude longitude:coordinate.longitude];

Related

create CLLocation object in objective-c

I can initialize a CLLocation object by providing latitude and longitude like below:
CLLocation *location = [[CLLocation alloc] initWithLatitude:-43.242534 longitude:-54.93662];
How can I initialize a CLLocation object with not only latitude and longitude but also accuracy values?
As per apple docs you can use the following function:
double desired_horizontal_accuracy = 200.0 // in meters
double desired_vertical_accuracy = 200.0 // in meters
[[CLLocation alloc] initWithCoordinate:CLLocationCoordinate2DMake(-43.242534,-54.93662)
altitude:-1
horizontalAccuracy:desired_horizontal_accuracy
verticalAccuracy:desired_vertical_accuracy
timestamp:[NSDate date]]
In the example, for the parameters altitude and timestamp, I put the same defaults as what the apple docs say are used on -initWithLatitude:longitude:

iOS: Create CLLocation with latitude, longitude, speed and timestamp

I'm want to initialize a CLLocation object. To do this I'm using:
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
My location need speed and timestamp, but speed and timestamp are read only parameters. How can I assign values to this parameters?
I have found the solution:
initWithCoordinate:altitude:horizontalAccuracy:verticalAccuracy:course:speed:timestamp:
More info: Apple doc for CLLocation.

Distance from UITableView Cells and Current Location

I am creating an iOS application where I have some data structure containing multiple coordinates and I know the current user location. I want to fill the cells of the TableView with the distance from the user's current location to the locations in the TableView.
I was wondering when I should calculate the distance between the user's current location and all the locations in the TableView. Should I calculate all these distances when the application starts? What should I do when the user changes location? Set some sort of timer to check if the user's position changed and recalculate the distances every time the user's position changed?
I should also note, I am giving them the ability to sort this TableView by distance.
Thanks in advance.
You can user CLLocationManagerDelegate's locationManager:didUpdateLocations: Method.
This method is called when user's location will update so you can call your method to show data in tableview from user's current location.
below is some code for sorting your arryOfLocation.
for (int i = 0; i < arrySortByLocation.count; i++)
{
//Current Location Details
NSMutableDictionary *dict = [[arrySortByLocation objectAtIndex:i] mutableCopy];
CLLocationDegrees latitude = [dict[#"city_lat"] doubleValue];
CLLocationDegrees longitude = [dict[#"city_lng"] doubleValue];
CLLocation *location = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
CLLocationDistance distance = [appDele.userLocation distanceFromLocation:location];
dict[#"distance"] = [#(distance) stringValue];
//Storing as string since latitude and longitude is also string values
//Since its a dictionary storing as NSNumber is better
[arrySearchLocation setObject:dict atIndexedSubscript:i];
}
//sorting based on distance
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"distance.doubleValue" ascending:YES];
[arrySortByLocation sortUsingDescriptors:#[descriptor]];
}
Hope this will help you..

How to convert PFGeoPoint to CLLocation

Is it possible to convert the PFGeoPoint with Parse to a CLLocation?
Reason being I'm trying to get the names of places from PFGeoPoint like so:
CLGeocoder *geocoder;
CLPlacemark *placemark;
PFGeoPoint *point = [object objectForKey:#"location"];
[geocoder reverseGeocodeLocation:point completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0)
{
placemark = [placemarks lastObject];
NSLog(#"%#", placemarks);
}
}];
Error I get obviously is:
Incompatiable pointer types sending 'PFGeoPoint *' to parameter of type 'CLLocation *'
As Wain said there is no convenient method to convert from PFGeoPoint to a CLLocation however you can make your own and extend PFGeoPoint using the following
import Parse
extension PFGeoPoint {
func location() -> CLLocation {
return CLLocation(latitude: self.latitude, longitude: self.longitude)
}
}
now you can easily return a CLLocation object by doing
let aLocation: CLLocation = yourGeoPointObject.location()
You need to explicitly create the CLLocation instance using initWithLatitude:longitude: with the latitude and longitude from the PFGeoPoint. There is only a convenience method for creating a PFGeoPoint from a CLLocation, not the other way round.
Based on Justin Oroz's answer (see the answer below):
Also a great idea could be to create the extension in the CLLocation side so it can be created using a convenience init which receives the PFGeoPoint:
extension CLLocation {
convenience init(geoPoint: PFGeoPoint) {
self.init(latitude: geoPoint.latitude, longitude: geoPoint.longitude)
}
}
You could always get the PFGeoPoint and then add it to a CLLocationCoordinate2D like this:
//get all PFObjects
let parseLocation = ParseObject["location"]
let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: parseLocation.latitude, longitude: parseLocation.longitude)

Sending CLLocationCoordinate2D to parameter of incompatible type my code in Xcode 4.5

I am new to Xcode. I am developing a vehicle tracking app for that I need to display more annotation points simultaneously. For this I need to store the coordinates in the array but it shows the error: Sending CLLocationCoordinate2D to parameter of incompatible type
my code is:
NSString *urlMapString=[NSString stringWithFormat:#"http://logix.com/logix_webservice/mapvehiclelist.php?uid=20&format=json"];
NSURL *urlMap=[NSURL URLWithString:urlMapString];
NSData *dataMap=[NSData dataWithContentsOfURL:urlMap];
if(dataMap!=NULL){
NSError *errorMap;
NSMutableArray *coordinates = [[NSMutableArray alloc]init];
NSDictionary *jsonMap = [NSJSONSerialization JSONObjectWithData:dataMap options:kNilOptions error:&errorMap];
NSArray *resultsMap = [jsonMap valueForKey:#"posts"];
for(int count=1;count<resultsMap.count;count++)
{
NSDictionary *resMap = [[resultsMap objectAtIndex:count]valueForKey:#"post"];
NSString *latOrgstring =[resMap valueForKey:#"latitude"];
latitude=[latOrgstring doubleValue];
NSString *longitudeString=[resMap valueForKey:#"longitude"];
longitude=[longitudeString doubleValue];
//Center
CLLocationCoordinate2D center;
center.latitude=latitude;
center.longitude=longitude;
[coordinates addObject:center]; //here it shows the error
}
}
Kindly advice me to solve this problem.
Thank you...
CLLocationCoordinate2D center isn't an object. You can store only objects in NSArray.
Use CLLocation for this.
CLLocation *location = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
As already mentioned, you can only add objects to an NSArray.
CLLocationCoordinate2D is not an object -- it is a C struct.
The code you posted itself has one solution:
Create a NSDictionary with the latitude and longitude as key/value pairs and add the resulting dictionary object to the array.
Another approach is to create a CLLocation as shown in another answer.
A third idea is what #trojanfoe answered previously which is to wrap the struct in an NSValue.
However, note that there is a convenient NSValue addition specifically for MapKit that adds these two useful helper methods:
valueWithMKCoordinate: which returns an NSValue given a CLLocationCoordinate2D
MKCoordinateValue which returns a CLLocationCoordinate2D for the NSValue
For an example, see How to store CLLocationCoordinate2D?.
A final (at least in this answer) alternate approach which I would highly recommend instead of all the above is this...
Why do you want to store only the coordinates in an array?
Wouldn't you want to know what the coordinates are for (which vehicle, place, etc)?
Why not create a custom class that implements, say, the MKAnnotation protocol and has not only the coordinates (as a CLLocationCoordinate2D property) but also all the other information related to the coordinate? The class would be a subclass of NSObject<MKAnnotation>.
You could then conveniently access all the information in one place without using multiple arrays and trying to keep the objects in the same order so they all have the same index, etc.
You could then directly add these objects to an MKMapView since they implement MKAnnotation.
CLLocationCoordinate2D is a C struct, so you need to put it in NSValue container at first.
An NSValue object is a simple container for a single C or Objective-C
data item. It can hold any of the scalar types such as int, float, and
char, as well as pointers, structures, and object id references. Use
this class to work with such data types in collections (such as
NSArray and NSSet), key-value coding, and other APIs that require
Objective-C objects.
[coordinates addObject:[NSValue value:&coordinate withObjCType:#encode(CLLocationCoordinate2D)]];
Try this
CLLocationCoordinate2D new_coordinate = CLLocationCoordinate2DMake(latitude, longitude);
[points addObject:[NSValue valueWithMKCoordinate:new_coordinate]];
Or
CLLocation *location = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
[coordinates addObject: location];
Can't u directly add coordinates to mapview that means Place MKAnnotation on Mapview, instead of taking coordinates to into array ?
SEE Below i commented with lines
for(int count=1;count<resultsMap.count;count++)
{
NSDictionary *resMap = [[resultsMap objectAtIndex:count]valueForKey:#"post"];
NSString *latOrgstring =[resMap valueForKey:#"latitude"];
latitude=[latOrgstring doubleValue];
NSString *longitudeString=[resMap valueForKey:#"longitude"];
longitude=[longitudeString doubleValue];
//Center
CLLocationCoordinate2D center;
center.latitude=latitude;
center.longitude=longitude;
-----------------------------------------
////// Annotation is MKAnnotation Subclass
Annotation * cartAnn = [Annotation new];
cartAnn.coordinate = center;
[self.mapView addAnnotation: cartAnn];
----------------------------------------------------
/////// [coordinates addObject:center]; //here it shows the error
}

Resources