forked from rsjohnson/MDSGeocoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMDSGeocodingViewController.m
264 lines (197 loc) · 10.6 KB
/
MDSGeocodingViewController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
//
// MDSGeocodingViewController.m
// Map Kit Demo
//
// Created by Ryan Johnson on 3/18/12.
// Copyright (c) 2012 mobile data solutions.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#import <CoreLocation/CoreLocation.h>
#import <AddressBookUI/AddressBookUI.h>
#import "MDSGeocodingViewController.h"
@interface MDSGeocodingViewController ()
{
IBOutlet MKMapView * _mapView;
NSMutableArray * _geocodingResults;
CLGeocoder * _geocoder;
NSTimer * _searchTimer;
}
- (void) geocodeFromTimer:(NSTimer *)timer;
- (void) processForwardGeocodingResults:(NSArray *)placemarks;
- (void) processReverseGeocodingResults:(NSArray*)placemarks;
- (void) reverseGeocodeCoordinate:(CLLocationCoordinate2D)coord;
- (IBAction) didLongPress:(UILongPressGestureRecognizer*)gr;
- (void) addPinAnnotationForPlacemark:(CLPlacemark*)placemark;
- (void) zoomMapToPlacemark:(CLPlacemark *)selectedPlacemark;
-(void) setActivePlacemark:(CLPlacemark*)selectedPlacemark;
@end
@implementation MDSGeocodingViewController
+ (MDSGeocodingViewController*) viewController
{
return [[self alloc] initWithNibName:@"MDSGeocodingViewController" bundle:nil];
}
- (void) viewDidLoad {
[super viewDidLoad];
[self.searchDisplayController.searchBar setPlaceholder:NSLocalizedString(@"Custom Location", @"location name prompt on search bar")];
[self setTitle:NSLocalizedString(@"Set Location", @"prompt for how to use location map")];
[self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"here", @"Show user's current location on map") style:UIBarButtonItemStyleBordered target:self action:@selector(currentLocationButtonPressed:)]];
_geocodingResults = [NSMutableArray array];
_geocoder = [[CLGeocoder alloc] init];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Geocoding Methods
NSString * const kSearchTextKey = @"Search Text"; /*< NSDictionary key for entered search text. Used by NSTimer userInfo.*/
- (void) geocodeFromTimer:(NSTimer *)timer {
NSString * searchString = [timer.userInfo objectForKey:kSearchTextKey];
// Cancel any active geocoding. Note: Cancelling calls the completion handler on the geocoder
if (_geocoder.isGeocoding)
[_geocoder cancelGeocode];
[_geocoder geocodeAddressString:searchString
completionHandler:^(NSArray *placemark, NSError *error) {
if (!error)
[self processForwardGeocodingResults:placemark];
}
];
}
- (void) processForwardGeocodingResults:(NSArray *)placemarks {
[_geocodingResults removeAllObjects];
[_geocodingResults addObjectsFromArray:placemarks];
[self.searchDisplayController.searchResultsTableView reloadData];
}
- (void) didLongPress:(UILongPressGestureRecognizer *)gr {
if (gr.state == UIGestureRecognizerStateBegan) {
// convert the touch point to a CLLocationCoordinate & geocode
CGPoint touchPoint = [gr locationInView:_mapView];
CLLocationCoordinate2D coord = [_mapView convertPoint:touchPoint
toCoordinateFromView:_mapView];
[[NSNotificationCenter defaultCenter] postNotificationName:@"GeoSetCustomUserLocation" object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"location",[[CLLocation alloc] initWithCoordinate:coord altitude:0 horizontalAccuracy:0 verticalAccuracy:0 timestamp:nil], nil]];
[self reverseGeocodeCoordinate:coord];
}
}
- (void) reverseGeocodeCoordinate:(CLLocationCoordinate2D)coord {
if ([_geocoder isGeocoding])
[_geocoder cancelGeocode];
CLLocation * location = [[CLLocation alloc] initWithLatitude:coord.latitude
longitude:coord.longitude];
[_geocoder reverseGeocodeLocation:location
completionHandler:^(NSArray *placemarks, NSError *error) {
if (!error)
[self processReverseGeocodingResults:placemarks];
}];
}
- (void) processReverseGeocodingResults:(NSArray *)placemarks {
if ([placemarks count] == 0)
return;
CLPlacemark * placemark = [placemarks objectAtIndex:0];
[[NSNotificationCenter defaultCenter] postNotificationName:@"GeoSetCustomUserLocation" object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[placemark location],@"location", nil]];
[self setActivePlacemark:placemark];
}
- (void) addPinAnnotationForPlacemark:(CLPlacemark*)placemark {
MKPointAnnotation * placemarkAnnotation = [[MKPointAnnotation alloc] init];
placemarkAnnotation.coordinate = placemark.location.coordinate;
placemarkAnnotation.title = ABCreateStringWithAddressDictionary(placemark.addressDictionary, NO);
[_mapView addAnnotation:placemarkAnnotation];
}
- (void) zoomMapToPlacemark:(CLPlacemark *)selectedPlacemark {
CLLocationCoordinate2D coordinate = selectedPlacemark.location.coordinate;
MKMapPoint mapPoint = MKMapPointForCoordinate(coordinate);
double radius = (MKMapPointsPerMeterAtLatitude(coordinate.latitude) * selectedPlacemark.region.radius)/2;
if (radius == 0)
radius = 10000;
MKMapSize size = {radius, radius};
MKMapRect mapRect = {mapPoint, size};
mapRect = MKMapRectOffset(mapRect, -radius/2, -radius/2); // adjust the rect so the coordinate is in the middle
[_mapView setVisibleMapRect:mapRect animated:YES];
}
#pragma mark - UISearchDisplayController Delegate Methods
- (BOOL) searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
// Use a timer to only start geocoding when the user stops typing
if ([_searchTimer isValid])
[_searchTimer invalidate];
const NSTimeInterval kSearchDelay = .25;
NSDictionary * userInfo = [NSDictionary dictionaryWithObject:searchString
forKey:kSearchTextKey];
_searchTimer = [NSTimer scheduledTimerWithTimeInterval:kSearchDelay
target:self
selector:@selector(geocodeFromTimer:)
userInfo:userInfo
repeats:NO];
return NO;
}
#pragma mark - UITableView Data Source + Delegate Methods
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_geocodingResults count];
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString * const kCellIdentifier = @"Cell";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
if (!cell)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:kCellIdentifier];
CLPlacemark * placemark = [_geocodingResults objectAtIndex:indexPath.row];
NSString * formattedAddress = ABCreateStringWithAddressDictionary(placemark.addressDictionary, NO);
cell.textLabel.text = formattedAddress;
return cell;
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
CLPlacemark * selectedPlacemark = [_geocodingResults objectAtIndex:indexPath.row];
[[NSNotificationCenter defaultCenter] postNotificationName:@"GeoSetCustomUserLocation" object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[selectedPlacemark location],@"location", nil]];
[self setActivePlacemark:selectedPlacemark];
}
-(void) setActivePlacemark:(CLPlacemark*)selectedPlacemark{
[_mapView setShowsUserLocation:FALSE];
// Clear the map
[_mapView removeAnnotations:_mapView.annotations];
[self addPinAnnotationForPlacemark:selectedPlacemark];
[self.searchDisplayController.searchBar setPlaceholder:[selectedPlacemark locality]];
// hide the search display controller and reset the search results
[self.searchDisplayController setActive:NO animated:YES];
[_geocodingResults removeAllObjects];
[self zoomMapToPlacemark:selectedPlacemark];
}
-(void)currentLocationButtonPressed:(id)sender{
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"enable location usage" , @"prompt when denied usage of current location in app and user wants current location") message:NSLocalizedString(@"see location in settings and enable TourBus", @"tells user where to look for setting") delegate:nil cancelButtonTitle:NSLocalizedString(@"Okay", @"Accept button on error alert") otherButtonTitles:nil]show];
}
[self.searchDisplayController.searchBar setPlaceholder:NSLocalizedString(@"Custom Location", @"location name prompt on search bar")];
[[NSNotificationCenter defaultCenter] postNotificationName:@"GeoTrackActiveUserLocation" object:self userInfo:nil];
[self trackUserLocation];
}
-(void) setCustomUserLocation:(CLLocation*)userLocation{
if (userLocation)
[self reverseGeocodeCoordinate:userLocation.coordinate];
}
-(void) trackUserLocation{
[_mapView removeAnnotations:_mapView.annotations];
[_mapView setUserTrackingMode:MKUserTrackingModeFollow];
[_mapView setShowsUserLocation:TRUE];
}
#pragma mark - MKMapView Delegate Methods
- (MKAnnotationView*) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
static NSString * const kPinIdentifier = @"Pin";
MKPinAnnotationView * pin = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:kPinIdentifier];
if (!pin)
pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:kPinIdentifier];
pin.annotation = annotation;
return pin;
}
@end