There must be an easy way to do this or somewhere I am going wrong but I can't seem to save my current location as a global variable and then add it to my array to populate my UITableView.
Basically, at the moment I have an empty UITableView that is used to populate results from a local search, via a search bar. This part works great. BUT, what I want is to always have the 1st row as the users current location, like in maps, google maps, reminders etc. I figured this would be a simple task but I cant get it to work. Can someone help me please.
I use the following code to get my current location, reverse geocode it, and plot it on the map when the app starts:
self.locationManager = [[CLLocationManager alloc]init];
if ([CLLocationManager locationServicesEnabled]) {
self.locationManager.delegate = self;
self.locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
}
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = _locationManager.location.coordinate.latitude;
zoomLocation.longitude= _locationManager.location.coordinate.longitude;
currentCoord.latitude = _locationManager.location.coordinate.latitude;
currentCoord.longitude= _locationManager.location.coordinate.longitude;
//reverse geocoder
CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:zoomLocation.latitude longitude:zoomLocation.longitude];
CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *placemark in placemarks) {
MKPointAnnotation *annotation =
[[MKPointAnnotation alloc]init];
annotation.coordinate = zoomLocation;
annotation.title = #"Current Location";
annotation.subtitle = placemark.name;
// 2
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
// 3
[_mapView setRegion:viewRegion animated:YES];
[_mapView addAnnotation:annotation];
}
}];
When I run my local search I use the following code to populate my array to load the table with:
MKLocalSearchRequest *request =
[[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = _searchBar.text;
request.region = _mapView.region;
MKLocalSearch *search =
[[MKLocalSearch alloc]initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse
*response, NSError *error) {
if (response.mapItems.count == 0)
NSLog(#"No Matches");
else
for (MKMapItem *item in response.mapItems)
{
[tableData addObject:item];
MKPointAnnotation *annotation =
[[MKPointAnnotation alloc]init];
annotation.coordinate = item.placemark.coordinate;
annotation.title = item.placemark.name;
annotation.subtitle = item.placemark.title;
[annotations addObject:annotation];
[_tableResults reloadData];
}
}];
I really can't figure this out. How would I add my current location? Would really appreciate some advise. Thanks in advance guys!
Try this,
[search startWithCompletionHandler:^(MKLocalSearchResponse
*response, NSError *error) {
if (response.mapItems.count == 0)
NSLog(#"No Matches");
else
for (MKMapItem *item in response.mapItems)
{
[tableData addObject:item];
[annotations addObject:[self annotationFromMapItem:item]];
}
double latitude = self.locationManager.location.coordinate.latitude;
double longitude = self.locationManager.location.coordinate.longitude;
MKPlacemark *placemark = [[[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake(latitude, longitude) addressDictionary:nil] autorelease];
MKMapItem *mapItem = [[[MKMapItem alloc] initWithPlacemark:placemark] autorelease];
[mapItem setName:Current Location];
[tableData insertObject:mapItem atIndex:0];
[annotations insertObject:[self annotationFromMapItem:mapItem] atIndex:0];
[_tableResults reloadData];
}];
- (MKPointAnnotation) annotationFromMapItem:(MKMapItem *)item {
MKPointAnnotation *annotation =
[[MKPointAnnotation alloc]init];
annotation.coordinate = item.placemark.coordinate;
annotation.title = item.placemark.name;
annotation.subtitle = item.placemark.title;
return annotation;
}
Related
I'm using the below code to display addresses from an array (responseObject) as annotations on my mapview. It works, and the pin is dropped successfully from my location string, however it only shows a pin for the most recent address added to the array. How can I change my code so that it shows pins on the map for all addresses in my array instead of just the most recent one? Apologies if this is a newb question. Thanks!
viewcontroller.m
NSMutableDictionary *viewParams = [NSMutableDictionary new];
[viewParams setValue:#"u000" forKey:#"view_name"];
[DIOSView viewGet:viewParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.addressData = [responseObject mutableCopy];
NSString *location = self.addressData[0][#"address"];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:location
completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
MKCoordinateRegion region = self.mapView.region;
// region.center = placemark.region.center;
region.span.longitudeDelta /= 8.0;
region.span.latitudeDelta /= 8.0;
[self.mapView setRegion:region animated:YES];
[self.mapView addAnnotation:placemark];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = placemark.coordinate;
point.title = self.addressData[0][#"users_name"];
point.subtitle = self.addressData[0][#"userbio"];
[self.mapView addAnnotation:point];
You are accessing only one object ?
NSString *location = self.addressData[0][#"address"];
Edited
I think you should handle your data, separated with your view. i.e. implement geocoder related code in the mapView:viewForAnnotation: method in your map view delegate. Then you should be able to create the annotations one by one and use [self.mapView addAnnotations] for all of them
For your code, which I believe is inspired by this answer, you should be able to iterate through all location addresses by something like
for (NSMutableDictionary *loc in self.addressData) {
NSString *loc = location[#"address"];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
......
}
Forgive me if the syntax is wrong for Objective C.
I want to search for a destination using the name in MapKit and get back the longitude and latitude (CLLocationCoordinate2D).
Currently I'm using the hardcoded value to set the destination.
// Make a directions request
MKDirectionsRequest *directionsRequest = [MKDirectionsRequest new];
// Start at our current location
MKMapItem *source = [MKMapItem mapItemForCurrentLocation];
[directionsRequest setSource:source];
// Make the destination --> I WANT TO GET THIS COORDINATE USING NAME
CLLocationCoordinate2D destinationCoords = CLLocationCoordinate2DMake(45.545824, 9.327515);
MKPlacemark *destinationPlacemark = [[MKPlacemark alloc] initWithCoordinate:destinationCoords addressDictionary:nil];
MKMapItem *destination = [[MKMapItem alloc] initWithPlacemark:destinationPlacemark];
[directionsRequest setDestination:destination];
You have to use CLGeocoder to forward-geocode using an address:
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:#"New York City" completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
CLPlacemark *placemark = [placemarks lastObject];
MKCoordinateRegion region;
region.center.latitude = placemark.location.coordinate.latitude;
region.center.longitude = placemark.location.coordinate.longitude;
[self.mapView setRegion:region animated:YES];
}
}];
This will set the map's region to the location returned, using the latitude and longitude as it's centre.
So let's say I'm trying to search for a query within 1 mile radius of the user's current location. Here's my search code so far:
- (void) performLocalSearch{
MKLocalSearchRequest *searchRequest = [[MKLocalSearchRequest alloc] init];
searchRequest.naturalLanguageQuery = _searchText;
MKCoordinateRegion searchRegion;
searchRegion.center.latitude = userLocation.coordinate.latitude;
searchRegion.center.longitude = userLocation.coordinate.longitude;
searchRegion.span.latitudeDelta = 0.0144927536231884;
searchRegion.span.longitudeDelta = 0.0144927536231884;
searchRequest.region = searchRegion;
MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:searchRequest];
[search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
for (MKMapItem *item in response.mapItems) {
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.title = item.name;
annotation.coordinate = item.placemark.coordinate;
[_map addAnnotation:annotation];
}
}
];
}
When I run the code on my device, pins show up on the map, but they are not within the specified radius. I also tried using MKCoordinateRegionMakeWithDistance to set the search region but I couldn't figure out how to cast the double radius value as a CLLocationDistance object. Any help would be appreciated. Thanks.
The code below is for conducting search with MKLocalSearch and loading the results into an array.
This array gets passed to my [self.mapView addAnnotations:annotations] method. Everything works great until I try to dismiss this viewcontroller by tapping the back button (in my navigation bar for storyboards).
I get EXC_BAD_ACCESS(code=1, address=0x4). If I comment out the Show Pins section below the problem goes away (but of course I am now not loading my annotations).
Please help!
-(void)issueLocalSearchLookup:(NSString *)searchString usingPlacemarksArray:(NSArray *)placemarks {
self.coords = mapView.userLocation.coordinate;
// Set the size of the region we want to get search results for.
MKCoordinateSpan span = MKCoordinateSpanMake(0.001250, 0.001250);
MKCoordinateRegion region = MKCoordinateRegionMake(mapView.userLocation.coordinate, span);
[self.mapView setRegion:region animated:YES];
// Create the search request
self.localSearchRequest = [[MKLocalSearchRequest alloc] init];
self.localSearchRequest.region = region;
self.localSearchRequest.naturalLanguageQuery = searchString;
// Perform the search request...
self.localSearch = [[MKLocalSearch alloc] initWithRequest:self.localSearchRequest];
[self.localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
if(error){
NSLog(#"localSearch startWithCompletionHandlerFailed! Error: %#", error);
return;
} else {
// We are here because we have data!
for(MKMapItem *mapItem in response.mapItems){
// Show pins...
NSMutableArray *annotations = [NSMutableArray array];
Annotation *annotation = [[Annotation alloc] initWithCoordinate: mapItem.placemark.location.coordinate];
annotation.title = mapItem.name;
annotation.subtitle = mapItem.placemark.addressDictionary[(NSString *)kABPersonAddressStreetKey];
[mapView addAnnotation:annotation];
NSLog(#"Name for result: = %#", mapItem.name);
[self.mapView addAnnotations:annotations];
NSLog(#"Name for result: = %#", mapItem.name);
}
MKCoordinateSpan span = MKCoordinateSpanMake(0.01, 0.01);
MKCoordinateRegion region = MKCoordinateRegionMake(self.coords, span);
[self.mapView setRegion:region animated:YES];
}
}];
}
I had set my custom annotation to be a subclass of NKPlacemark....I needed to have it be a subclass of NSObject.
Hi am using this method to get the coordinates and add a pin to the map view for one post code
-(void)myMapview
{
//sitePC is an Array with the Post code location
NSString *addressString = [self.sitePC valueForKey:#"sitePC"];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:addressString completionHandler:^(NSArray *placemarks, NSError *anError)
{ for(CLPlacemark *placemark in placemarks) {
NSLog(#"Placemark: %#",placemark);
MKPointAnnotation *pa = [[MKPointAnnotation alloc] init];
pa.coordinate = placemark.location.coordinate;
pa.title = [self.sitePC valueForKey:#"siteName"];
[self.mapview addAnnotation:pa];
} if(anError)
{ NSLog(#"Error: %#",[anError description]); }
}];
}
but now the sitePC array hold 10 post codes to process, I read the Documents for CLGeocoder and I know I can only send one request at the time.
my question is how do I send only one request at the time , for each postcode ?
You can make an Array for annotations and Add that annotation array on MapView . Hope following changes in code will help you.
NSString *addressString = [self.sitePC valueForKey:#"sitePC"];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:addressString completionHandler:^(NSArray *placemarks, NSError *anError)
{
NSMutableArray *pointsArray = [[NSMutableArray alloc]init]
for(CLPlacemark *placemark in placemarks) {
NSLog(#"Placemark: %#",placemark);
MKPointAnnotation *pa = [[MKPointAnnotation alloc] init];
pa.coordinate = placemark.location.coordinate;
pa.title = [self.sitePC valueForKey:#"siteName"];
[pointsArray addObject:pa];
}
[self.mapview addAnnotations:pointsArray];
if(anError)
{ NSLog(#"Error: %#",[anError description]); }
}];