GeocoderViewController.m 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright 2016 Google Inc. All rights reserved.
  3. *
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
  6. * file except in compliance with the License. You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software distributed under
  11. * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  12. * ANY KIND, either express or implied. See the License for the specific language governing
  13. * permissions and limitations under the License.
  14. */
  15. #import "GoogleMapsDemos/Samples/GeocoderViewController.h"
  16. #import <GoogleMaps/GoogleMaps.h>
  17. @implementation GeocoderViewController {
  18. GMSMapView *_mapView;
  19. GMSGeocoder *_geocoder;
  20. }
  21. - (void)viewDidLoad {
  22. [super viewDidLoad];
  23. GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
  24. longitude:151.2086
  25. zoom:12];
  26. _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  27. _mapView.delegate = self;
  28. _geocoder = [[GMSGeocoder alloc] init];
  29. self.view = _mapView;
  30. }
  31. - (void)mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate {
  32. // On a long press, reverse geocode this location.
  33. __weak typeof(self) weakSelf = self;
  34. GMSReverseGeocodeCallback handler = ^(GMSReverseGeocodeResponse *response, NSError *error) {
  35. [weakSelf handleResponse:response coordinate:coordinate error:error];
  36. };
  37. [_geocoder reverseGeocodeCoordinate:coordinate completionHandler:handler];
  38. }
  39. - (void)handleResponse:(nullable GMSReverseGeocodeResponse *)response
  40. coordinate:(CLLocationCoordinate2D)coordinate
  41. error:(nullable NSError *)error {
  42. GMSAddress *address = response.firstResult;
  43. if (address) {
  44. NSLog(@"Geocoder result: %@", address);
  45. GMSMarker *marker = [GMSMarker markerWithPosition:address.coordinate];
  46. NSArray<NSString *> *lines = [address lines];
  47. marker.title = [lines firstObject];
  48. if (lines.count > 1) {
  49. marker.snippet = [lines objectAtIndex:1];
  50. }
  51. marker.appearAnimation = kGMSMarkerAnimationPop;
  52. marker.map = _mapView;
  53. } else {
  54. NSLog(@"Could not reverse geocode point (%f,%f): %@", coordinate.latitude, coordinate.longitude,
  55. error);
  56. }
  57. }
  58. @end