เลือกสถานที่ปัจจุบันและแสดงรายละเอียดบนแผนที่

บทแนะนำนี้จะแสดงวิธีสร้างแอป iOS เพื่อทำสิ่งต่อไปนี้

  • รับตำแหน่งปัจจุบันของอุปกรณ์
  • ดูรายการสถานที่ที่อุปกรณ์น่าจะอยู่
  • แจ้งให้ผู้ใช้หาสถานที่ที่เหมาะสมที่สุด
  • แสดงเครื่องหมายบนแผนที่

ทำตามบทแนะนำนี้เพื่อสร้างแอป iOS โดยใช้ Places SDK สำหรับ iOS, Maps SDK สำหรับ iOS และเฟรมเวิร์กตำแหน่งหลักของ Apple

กำลังรับรหัส

โคลนหรือดาวน์โหลด Google Maps SDK สำหรับ iOS จาก GitHub

กำลังตั้งค่าโปรเจ็กต์การพัฒนาของคุณ

ปฏิบัติตามขั้นตอนต่อไปนี้เพื่อติดตั้ง Places SDK สำหรับ iOS และ Maps SDK สำหรับ iOS

  1. ดาวน์โหลดและติดตั้ง Xcode เวอร์ชัน 14.0 ขึ้นไป
  2. หากยังไม่มี CocoaPods ให้ติดตั้งใน macOS โดยเรียกใช้คำสั่งต่อไปนี้จากเทอร์มินัล
    sudo gem install cocoapods
  3. ในไดเรกทอรีที่คุณบันทึกที่เก็บตัวอย่าง (รับโค้ด) ให้ไปที่ไดเรกทอรี tutorials/current-place-on-map
  4. เรียกใช้คำสั่ง pod install การดำเนินการนี้จะติดตั้ง API ที่ระบุใน Podfile รวมถึงทรัพยากร Dependency ที่อาจมี
  5. เรียกใช้ pod outdated เพื่อเปรียบเทียบเวอร์ชันพ็อดที่ติดตั้งกับการอัปเดตใหม่ๆ หากตรวจพบเวอร์ชันใหม่ ให้เรียกใช้ pod update เพื่ออัปเดต Podfile และติดตั้ง SDK เวอร์ชันล่าสุด โปรดดูรายละเอียดเพิ่มเติมที่คู่มือ CocoaPods
  6. เปิด (ดับเบิลคลิก) current-place-on-map.xcworkspace ของโปรเจ็กต์เพื่อเปิดใน Xcode คุณต้องใช้ไฟล์ .xcworkspace เพื่อเปิดโปรเจ็กต์

สำหรับคำแนะนำในการติดตั้งโดยละเอียด โปรดดูที่ การเริ่มต้นใช้งาน (Maps) และ การเริ่มต้นใช้งาน (สถานที่)

การเปิดใช้ API ที่จำเป็นและรับคีย์ API

หากต้องการศึกษาบทแนะนำนี้ให้จบ คุณต้องมีคีย์ Google API ที่ได้รับอนุญาตให้ใช้ Maps SDK สำหรับ iOS และ Places API

  1. ทำตามวิธีการในเริ่มต้นใช้งาน Google Maps Platform เพื่อตั้งค่าบัญชีสำหรับการเรียกเก็บเงินและโปรเจ็กต์ที่เปิดใช้กับผลิตภัณฑ์ทั้งสองนี้
  2. ทำตามวิธีการในหัวข้อรับคีย์ API เพื่อสร้างคีย์ API สำหรับโปรเจ็กต์การพัฒนาที่คุณตั้งค่าไว้ก่อนหน้านี้

การเพิ่มคีย์ API ลงในแอปพลิเคชัน

เพิ่มคีย์ API ไปยัง AppDelegate.swift ดังนี้

  1. โปรดทราบว่ามีการเพิ่มคำสั่งนำเข้าต่อไปนี้ลงในไฟล์
    import GooglePlaces
    import GoogleMaps
  2. แก้ไขบรรทัดต่อไปนี้ในเมธอด application(_:didFinishLaunchingWithOptions:) โดยแทนที่ YOUR_API_KEY ด้วยคีย์ API:
    GMSPlacesClient.provideAPIKey("YOUR_API_KEY")
    GMSServices.provideAPIKey("YOUR_API_KEY")

การสร้างและเรียกใช้แอป

  1. เชื่อมต่ออุปกรณ์ iOS กับคอมพิวเตอร์ หรือเลือกเครื่องมือจำลองจากเมนูป๊อปอัปรูปแบบ Xcode
  2. หากคุณใช้อุปกรณ์ โปรดตรวจสอบว่าได้เปิดใช้บริการตำแหน่งแล้ว หากคุณใช้เครื่องจำลอง ให้เลือกตำแหน่งจากเมนูฟีเจอร์
  3. ใน Xcode ให้คลิกตัวเลือกเมนู Product/Run (หรือไอคอนปุ่มเล่น)
    • Xcode จะสร้างแอป จากนั้นเรียกใช้แอปในอุปกรณ์หรือในเครื่องจำลอง
    • คุณควรเห็นแผนที่ซึ่งมีเครื่องหมายต่างๆ ตั้งศูนย์กลางรอบๆ ตำแหน่งปัจจุบันของคุณ

การแก้ปัญหา:

  • หากไม่เห็นแผนที่ ให้ตรวจสอบว่าคุณได้รับคีย์ API และเพิ่มไว้ในแอปแล้วตามที่อธิบายไว้ข้างต้น ตรวจสอบคอนโซลดีบักของ Xcode เพื่อหาข้อความแสดงข้อผิดพลาดเกี่ยวกับคีย์ API
  • หากคุณจำกัดคีย์ API ด้วยตัวระบุชุด iOS ให้แก้ไขคีย์เพื่อเพิ่มตัวระบุชุดของแอป: com.google.examples.current-place-on-map
  • แผนที่จะแสดงไม่ถูกต้อง ถ้าคำขอสิทธิ์สำหรับ บริการตำแหน่งถูกปฏิเสธ
    • หากคุณใช้อุปกรณ์ ให้ไปที่การตั้งค่า/ทั่วไป/ความเป็นส่วนตัว/บริการตำแหน่ง แล้วเปิดใช้บริการตำแหน่งอีกครั้ง
    • หากคุณใช้เครื่องจำลอง ให้ไปที่เครื่องจำลอง/รีเซ็ตเนื้อหาและการตั้งค่า...
    ครั้งต่อไปที่เรียกใช้แอป อย่าลืมยอมรับข้อความแจ้งเกี่ยวกับบริการตำแหน่ง
  • ตรวจสอบว่าการเชื่อมต่อ Wi-Fi หรือ GPS นั้นใช้งานได้ดี
  • หากแอปเปิดขึ้นแต่ไม่มีการแสดงแผนที่ ให้ตรวจสอบว่าคุณอัปเดต Info.plist สำหรับโปรเจ็กต์ด้วยสิทธิ์เข้าถึงตำแหน่งที่เหมาะสมแล้ว สำหรับข้อมูลเพิ่มเติมเกี่ยวกับการจัดการสิทธิ์ ให้ดูคำแนะนำในการขอสิทธิ์เข้าถึงตำแหน่งในแอปด้านล่าง
  • ใช้เครื่องมือแก้ไขข้อบกพร่อง Xcode เพื่อดูบันทึกและแก้ไขข้อบกพร่องของแอป

การทำความเข้าใจโค้ด

บทแนะนำในส่วนนี้จะอธิบายส่วนที่สำคัญที่สุดของแอปcurrent-place-on-map เพื่อช่วยให้คุณเข้าใจวิธีสร้างแอปที่คล้ายกัน

แอปcurrent-place-on-mapมีตัวควบคุมมุมมอง 2 อัน ได้แก่ ชุดหนึ่งแสดงแผนที่แสดงสถานที่ที่ผู้ใช้เลือกอยู่ ส่วนอีกอันหนึ่ง เพื่อนำเสนอรายการสถานที่ที่น่าจะเลือกไปให้ผู้ใช้ โปรดทราบว่าตัวควบคุมมุมมองแต่ละรายการมีตัวแปรเดียวกันสำหรับการติดตามรายการตำแหน่งที่น่าจะเป็น (likelyPlaces) และสำหรับระบุการเลือกของผู้ใช้ (selectedPlace) การไปยังมุมมองต่างๆ สามารถทำได้โดยใช้Segue

กำลังขอสิทธิ์เข้าถึงตำแหน่ง

แอปของคุณต้องแจ้งให้ผู้ใช้ขอความยินยอมในการใช้บริการตำแหน่ง โดยใส่คีย์ NSLocationAlwaysUsageDescription ในไฟล์ Info.plist ของแอป แล้วตั้งค่าของแต่ละคีย์เป็นสตริงที่อธิบายวิธีที่แอปจะใช้ข้อมูลตำแหน่ง

การตั้งค่าผู้จัดการสถานที่

ใช้ CLLocationManager เพื่อหาตำแหน่งปัจจุบันของอุปกรณ์และเพื่อขออัปเดตเป็นประจำเมื่ออุปกรณ์ย้ายไปยังตำแหน่งใหม่ บทแนะนำนี้มีโค้ดที่คุณต้องใช้ในการรับตำแหน่งของอุปกรณ์ สำหรับรายละเอียดเพิ่มเติม โปรดดูคู่มือการดูตำแหน่งของผู้ใช้ในเอกสารประกอบสำหรับนักพัฒนาซอฟต์แวร์ Apple

  1. ประกาศผู้จัดการสถานที่ ตำแหน่งปัจจุบัน มุมมองแผนที่ ตำแหน่งไคลเอ็นต์ และระดับการซูมเริ่มต้นที่ระดับชั้นเรียน
  2. Swift

    var locationManager: CLLocationManager!
    var currentLocation: CLLocation?
    var mapView: GMSMapView!
    var placesClient: GMSPlacesClient!
    var preciseLocationZoomLevel: Float = 15.0
    var approximateLocationZoomLevel: Float = 10.0
          

    Objective-C

    CLLocationManager *locationManager;
    CLLocation * _Nullable currentLocation;
    GMSMapView *mapView;
    GMSPlacesClient *placesClient;
    float preciseLocationZoomLevel;
    float approximateLocationZoomLevel;
          
  3. เริ่มต้นเครื่องมือจัดการสถานที่และ GMSPlacesClient ใน viewDidLoad()
  4. Swift

    // Initialize the location manager.
    locationManager = CLLocationManager()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.distanceFilter = 50
    locationManager.startUpdatingLocation()
    locationManager.delegate = self
    
    placesClient = GMSPlacesClient.shared()
          

    Objective-C

    // Initialize the location manager.
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager requestWhenInUseAuthorization];
    locationManager.distanceFilter = 50;
    [locationManager startUpdatingLocation];
    locationManager.delegate = self;
    
    placesClient = [GMSPlacesClient sharedClient];
          
  5. ประกาศตัวแปรเพื่อเก็บรายการสถานที่ที่เป็นไปได้ และสถานที่ที่ผู้ใช้เลือก
  6. Swift

    // An array to hold the list of likely places.
    var likelyPlaces: [GMSPlace] = []
    
    // The currently selected place.
    var selectedPlace: GMSPlace?
          

    Objective-C

    // An array to hold the list of likely places.
    NSMutableArray<GMSPlace *> *likelyPlaces;
    
    // The currently selected place.
    GMSPlace * _Nullable selectedPlace;
          
  7. เพิ่มผู้รับมอบสิทธิ์ให้จัดการกิจกรรมของผู้จัดการสถานที่โดยใช้ข้อกำหนดของส่วนขยาย
  8. Swift

    // Delegates to handle events for the location manager.
    extension MapViewController: CLLocationManagerDelegate {
    
      // Handle incoming location events.
      func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location: CLLocation = locations.last!
        print("Location: \(location)")
    
        let zoomLevel = locationManager.accuracyAuthorization == .fullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel
        let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude,
                                              longitude: location.coordinate.longitude,
                                              zoom: zoomLevel)
    
        if mapView.isHidden {
          mapView.isHidden = false
          mapView.camera = camera
        } else {
          mapView.animate(to: camera)
        }
    
        listLikelyPlaces()
      }
    
      // Handle authorization for the location manager.
      func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        // Check accuracy authorization
        let accuracy = manager.accuracyAuthorization
        switch accuracy {
        case .fullAccuracy:
            print("Location accuracy is precise.")
        case .reducedAccuracy:
            print("Location accuracy is not precise.")
        @unknown default:
          fatalError()
        }
    
        // Handle authorization status
        switch status {
        case .restricted:
          print("Location access was restricted.")
        case .denied:
          print("User denied access to location.")
          // Display the map using the default location.
          mapView.isHidden = false
        case .notDetermined:
          print("Location status not determined.")
        case .authorizedAlways: fallthrough
        case .authorizedWhenInUse:
          print("Location status is OK.")
        @unknown default:
          fatalError()
        }
      }
    
      // Handle location manager errors.
      func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        locationManager.stopUpdatingLocation()
        print("Error: \(error)")
      }
    }
          

    Objective-C

    // Delegates to handle events for the location manager.
    #pragma mark - CLLocationManagerDelegate
    
    // Handle incoming location events.
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
    {
      CLLocation *location = locations.lastObject;
      NSLog(@"Location: %@", location);
    
      float zoomLevel = locationManager.accuracyAuthorization == CLAccuracyAuthorizationFullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel;
      GMSCameraPosition * camera = [GMSCameraPosition cameraWithLatitude:location.coordinate.latitude
                                                               longitude:location.coordinate.longitude
                                                                    zoom:zoomLevel];
    
      if (mapView.isHidden) {
        mapView.hidden = NO;
        mapView.camera = camera;
      } else {
        [mapView animateToCameraPosition:camera];
      }
    
      [self listLikelyPlaces];
    }
    
    // Handle authorization for the location manager.
    - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
    {
      // Check accuracy authorization
      CLAccuracyAuthorization accuracy = manager.accuracyAuthorization;
      switch (accuracy) {
        case CLAccuracyAuthorizationFullAccuracy:
          NSLog(@"Location accuracy is precise.");
          break;
        case CLAccuracyAuthorizationReducedAccuracy:
          NSLog(@"Location accuracy is not precise.");
          break;
      }
    
      // Handle authorization status
      switch (status) {
        case kCLAuthorizationStatusRestricted:
          NSLog(@"Location access was restricted.");
          break;
        case kCLAuthorizationStatusDenied:
          NSLog(@"User denied access to location.");
          // Display the map using the default location.
          mapView.hidden = NO;
        case kCLAuthorizationStatusNotDetermined:
          NSLog(@"Location status not determined.");
        case kCLAuthorizationStatusAuthorizedAlways:
        case kCLAuthorizationStatusAuthorizedWhenInUse:
          NSLog(@"Location status is OK.");
      }
    }
    
    // Handle location manager errors.
    - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
    {
      [manager stopUpdatingLocation];
      NSLog(@"Error: %@", error.localizedDescription);
    }
          

การเพิ่มแผนที่

สร้างแผนที่แล้วเพิ่มลงในมุมมองใน viewDidLoad() ในตัวควบคุมมุมมองหลัก แผนที่จะยังคงซ่อนอยู่จนกว่าจะได้รับการอัปเดตตำแหน่ง (การอัปเดตตำแหน่งจะดำเนินการในส่วนขยาย CLLocationManagerDelegate)

Swift

// A default location to use when location permission is not granted.
let defaultLocation = CLLocation(latitude: -33.869405, longitude: 151.199)

// Create a map.
let zoomLevel = locationManager.accuracyAuthorization == .fullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel
let camera = GMSCameraPosition.camera(withLatitude: defaultLocation.coordinate.latitude,
                                      longitude: defaultLocation.coordinate.longitude,
                                      zoom: zoomLevel)
mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
mapView.settings.myLocationButton = true
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.isMyLocationEnabled = true

// Add the map to the view, hide it until we've got a location update.
view.addSubview(mapView)
mapView.isHidden = true
      

Objective-C

// A default location to use when location permission is not granted.
CLLocationCoordinate2D defaultLocation = CLLocationCoordinate2DMake(-33.869405, 151.199);

// Create a map.
float zoomLevel = locationManager.accuracyAuthorization == CLAccuracyAuthorizationFullAccuracy ? preciseLocationZoomLevel : approximateLocationZoomLevel;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:defaultLocation.latitude
                                                        longitude:defaultLocation.longitude
                                                             zoom:zoomLevel];
mapView = [GMSMapView mapWithFrame:self.view.bounds camera:camera];
mapView.settings.myLocationButton = YES;
mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
mapView.myLocationEnabled = YES;

// Add the map to the view, hide it until we've got a location update.
[self.view addSubview:mapView];
mapView.hidden = YES;
      

การแจ้งให้ผู้ใช้เลือกสถานที่ปัจจุบัน

ใช้ Places SDK สำหรับ iOS เพื่อดูแนวโน้มของสถานที่ 5 อันดับแรกโดยอิงตามตำแหน่งปัจจุบันของผู้ใช้ และนำเสนอรายการใน UITableView เมื่อผู้ใช้เลือกสถานที่ ให้เพิ่มเครื่องหมายลงในแผนที่

  1. ดูรายการสถานที่ที่เป็นไปได้เพื่อป้อนข้อมูล UITableView ซึ่งผู้ใช้สามารถเลือกสถานที่ที่ตนอยู่ได้
  2. Swift

    // Populate the array with the list of likely places.
    func listLikelyPlaces() {
      // Clean up from previous sessions.
      likelyPlaces.removeAll()
    
      let placeFields: GMSPlaceField = [.name, .coordinate]
      placesClient.findPlaceLikelihoodsFromCurrentLocation(withPlaceFields: placeFields) { (placeLikelihoods, error) in
        guard error == nil else {
          // TODO: Handle the error.
          print("Current Place error: \(error!.localizedDescription)")
          return
        }
    
        guard let placeLikelihoods = placeLikelihoods else {
          print("No places found.")
          return
        }
    
        // Get likely places and add to the list.
        for likelihood in placeLikelihoods {
          let place = likelihood.place
          self.likelyPlaces.append(place)
        }
      }
    }
          

    Objective-C

    // Populate the array with the list of likely places.
    - (void) listLikelyPlaces
    {
      // Clean up from previous sessions.
      likelyPlaces = [NSMutableArray array];
    
      GMSPlaceField placeFields = GMSPlaceFieldName | GMSPlaceFieldCoordinate;
      [placesClient findPlaceLikelihoodsFromCurrentLocationWithPlaceFields:placeFields callback:^(NSArray<GMSPlaceLikelihood *> * _Nullable likelihoods, NSError * _Nullable error) {
        if (error != nil) {
          // TODO: Handle the error.
          NSLog(@"Current Place error: %@", error.localizedDescription);
          return;
        }
    
        if (likelihoods == nil) {
          NSLog(@"No places found.");
          return;
        }
    
        for (GMSPlaceLikelihood *likelihood in likelihoods) {
          GMSPlace *place = likelihood.place;
          [likelyPlaces addObject:place];
        }
      }];
    }
          
  3. เปิดมุมมองใหม่เพื่อนำเสนอสถานที่ที่เป็นไปได้ต่อผู้ใช้ เมื่อผู้ใช้แตะ "รับสถานที่" เราจะไปยังมุมมองใหม่และแสดงรายการของสถานที่ที่สามารถเลือกได้ ฟังก์ชัน prepare จะอัปเดต PlacesViewController ด้วยรายการสถานที่ที่เป็นไปได้ในปัจจุบัน และจะเรียกโดยอัตโนมัติเมื่อมีการ Segue
  4. Swift

    // Prepare the segue.
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if segue.identifier == "segueToSelect" {
        if let nextViewController = segue.destination as? PlacesViewController {
          nextViewController.likelyPlaces = likelyPlaces
        }
      }
    }
          

    Objective-C

    // Prepare the segue.
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
      if ([segue.identifier isEqualToString:@"segueToSelect"]) {
        if ([segue.destinationViewController isKindOfClass:[PlacesViewController class]]) {
          PlacesViewController *placesViewController = (PlacesViewController *)segue.destinationViewController;
          placesViewController.likelyPlaces = likelyPlaces;
        }
      }
    }
          
  5. ใน PlacesViewController ให้กรอกข้อมูลในตารางโดยใช้รายชื่อสถานที่ที่เป็นไปได้มากที่สุดโดยใช้ส่วนขยายผู้รับมอบสิทธิ์ UITableViewDataSource
  6. Swift

    // Populate the table with the list of most likely places.
    extension PlacesViewController: UITableViewDataSource {
      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return likelyPlaces.count
      }
    
      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath)
        let collectionItem = likelyPlaces[indexPath.row]
    
        cell.textLabel?.text = collectionItem.name
    
        return cell
      }
    }
          

    Objective-C

    #pragma mark - UITableViewDataSource
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
      return self.likelyPlaces.count;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
      return [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier forIndexPath:indexPath];
    }
    @end
          
  7. จัดการตัวเลือกของผู้ใช้โดยใช้ส่วนขยายการมอบสิทธิ์ UITableViewDelegate
  8. Swift

    class PlacesViewController: UIViewController {
    
      // ...
    
      // Pass the selected place to the new view controller.
      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "unwindToMain" {
          if let nextViewController = segue.destination as? MapViewController {
            nextViewController.selectedPlace = selectedPlace
          }
        }
      }
    }
    
    // Respond when a user selects a place.
    extension PlacesViewController: UITableViewDelegate {
      func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedPlace = likelyPlaces[indexPath.row]
        performSegue(withIdentifier: "unwindToMain", sender: self)
      }
    
      // Adjust cell height to only show the first five items in the table
      // (scrolling is disabled in IB).
      func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return self.tableView.frame.size.height/5
      }
    
      // Make table rows display at proper height if there are less than 5 items.
      func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if (section == tableView.numberOfSections - 1) {
          return 1
        }
        return 0
      }
    }
          

    Objective-C

    @interface PlacesViewController () <UITableViewDataSource, UITableViewDelegate>
    // ...
    
    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
    
    }
    
    #pragma mark - UITableViewDelegate
    
    // Respond when a user selects a place.
    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
      self.selectedPlace = [self.likelyPlaces objectAtIndex:indexPath.row];
      [self performSegueWithIdentifier:@"unwindToMain" sender:self];
    }
    
    // Adjust cell height to only show the first five items in the table
    // (scrolling is disabled in IB).
    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
      return self.tableView.frame.size.height/5;
    }
    
    // Make table rows display at proper height if there are less than 5 items.
    -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
    {
      if (section == tableView.numberOfSections - 1) {
        return 1;
      }
      return 0;
    }
          

การเพิ่มเครื่องหมายลงในแผนที่

เมื่อผู้ใช้ทำการเลือก ให้ใช้โหมดผ่อนคลายเพื่อกลับไปที่มุมมองก่อนหน้า และเพิ่มเครื่องหมายลงในแผนที่ unwindToMain IBAction จะถูกเรียกโดยอัตโนมัติเมื่อกลับไปที่ตัวควบคุมมุมมองหลัก

Swift

// Update the map once the user has made their selection.
@IBAction func unwindToMain(segue: UIStoryboardSegue) {
  // Clear the map.
  mapView.clear()

  // Add a marker to the map.
  if let place = selectedPlace {
    let marker = GMSMarker(position: place.coordinate)
    marker.title = selectedPlace?.name
    marker.snippet = selectedPlace?.formattedAddress
    marker.map = mapView
  }

  listLikelyPlaces()
}
      

Objective-C

// Update the map once the user has made their selection.
- (void) unwindToMain:(UIStoryboardSegue *)segue
{
  // Clear the map.
  [mapView clear];

  // Add a marker to the map.
  if (selectedPlace != nil) {
    GMSMarker *marker = [GMSMarker markerWithPosition:selectedPlace.coordinate];
    marker.title = selectedPlace.name;
    marker.snippet = selectedPlace.formattedAddress;
    marker.map = mapView;
  }

  [self listLikelyPlaces];
}
      

ยินดีด้วย คุณได้สร้างแอป iOS ที่ช่วยให้ผู้ใช้เลือกสถานที่ปัจจุบัน และแสดงผลการค้นหาบน Google Maps ระหว่างดำเนินการดังกล่าว คุณได้เรียนรู้วิธีใช้ Places SDK สำหรับ iOS, Maps SDK สำหรับ iOS และเฟรมเวิร์กตำแหน่งหลักของ Apple