मौजूदा जगह को चुनें और मैप पर जानकारी दिखाएं

इस ट्यूटोरियल में, ऐसा iOS ऐप्लिकेशन बनाने के बारे में बताया गया है जो डिवाइस की मौजूदा जगह की जानकारी पाने, संभावित जगहों की पहचान करने, उपयोगकर्ता को सबसे सही जगह चुनने का प्रॉम्प्ट, और चुनी गई जगह के लिए मैप मार्कर दिखाने के बारे में जानकारी देता है.

यह सुविधा उन लोगों के लिए सही है जिन्हें Swift या Objective-C के बारे में शुरुआती या इंटरमीडिएट जानकारी है और Xcode के बारे में सामान्य जानकारी है. मैप बनाने की बेहतर गाइड के लिए, डेवलपर गाइड पढ़ें.

इस ट्यूटोरियल का इस्तेमाल करके आप नीचे दिया गया मैप बनाएंगे. मैप मार्कर सैन फ़्रांसिस्को, कैलिफ़ोर्निया में स्थित है, लेकिन डिवाइस या सिम्युलेटर के स्थान पर चला जाएगा.

इस ट्यूटोरियल में, iOS के लिए Places SDK टूल, iOS के लिए Maps SDK टूल, और Apple Core लोकेशन फ़्रेमवर्क का इस्तेमाल किया गया है.

कोड पाएं

GitHub से Google Maps iOS सैंपल रिपॉज़िटरी का क्लोन बनाएं या उसे डाउनलोड करें.

इसके अलावा, सोर्स कोड को डाउनलोड करने के लिए, नीचे दिए गए बटन पर क्लिक करें:

मुझे कोड बताएं

Swift MapViewController

/*
 * Copyright 2016 Google Inc. All rights reserved.
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

import UIKit
import GoogleMaps
import GooglePlaces

class MapViewController: UIViewController {

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

  // An array to hold the list of likely places.
  var likelyPlaces: [GMSPlace] = []

  // The currently selected place.
  var selectedPlace: GMSPlace?

  // 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()
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    
    // Initialize the location manager.
    locationManager = CLLocationManager()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.distanceFilter = 50
    locationManager.startUpdatingLocation()
    locationManager.delegate = self

    placesClient = GMSPlacesClient.shared()

    // 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

    listLikelyPlaces()
  }

  // 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)
      }
    }
  }

  // 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
      }
    }
  }
}

// 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)")
  }
}

      

Swift PlacesViewController

/*
 * Copyright 2017 Google Inc. All rights reserved.
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

import UIKit
import GooglePlaces

class PlacesViewController: UIViewController {

  @IBOutlet weak var tableView: UITableView!

  // An array to hold the list of possible locations.
  var likelyPlaces: [GMSPlace] = []
  var selectedPlace: GMSPlace?

  // Cell reuse id (cells that scroll out of view can be reused).
  let cellReuseIdentifier = "cell"

  override func viewDidLoad() {
    super.viewDidLoad()

    // Register the table view cell class and its reuse id.
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

    // This view controller provides delegate methods and row data for the table view.
    tableView.delegate = self
    tableView.dataSource = self

    tableView.reloadData()
  }

  // 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
  }
}

// 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
  }
}

      

ऑब्जे-सी मैपव्यू कंट्रोलर

//
//  MapsViewController.m
//  current-place-on-map
//
//  Created by Chris Arriola on 9/18/20.
//  Copyright © 2020 William French. All rights reserved.
//

#import "MapViewController.h"
#import "PlacesViewController.h"
@import CoreLocation;
@import GooglePlaces;
@import GoogleMaps;

@interface MapViewController () <CLLocationManagerDelegate>

@end

@implementation MapViewController {
  CLLocationManager *locationManager;
  CLLocation * _Nullable currentLocation;
  GMSMapView *mapView;
  GMSPlacesClient *placesClient;
  float preciseLocationZoomLevel;
  float approximateLocationZoomLevel;
  
  // An array to hold the list of likely places.
  NSMutableArray<GMSPlace *> *likelyPlaces;

  // The currently selected place.
  GMSPlace * _Nullable selectedPlace;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  preciseLocationZoomLevel = 15.0;
  approximateLocationZoomLevel = 15.0;

  // Initialize the location manager.
  locationManager = [[CLLocationManager alloc] init];
  locationManager.desiredAccuracy = kCLLocationAccuracyBest;
  [locationManager requestWhenInUseAuthorization];
  locationManager.distanceFilter = 50;
  [locationManager startUpdatingLocation];
  locationManager.delegate = self;

  placesClient = [GMSPlacesClient sharedClient];

  // 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;

  [self listLikelyPlaces];
}

// 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];
    }
  }];
}

// 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];
}

// 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;
    }
  }
}

// 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);
}

@end

      

ऑब्जे-सी PlacesViewController

// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#import "PlacesViewController.h"

@interface PlacesViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, weak) UITableView *tableView;
@end

@implementation PlacesViewController {
  // Cell reuse id (cells that scroll out of view can be reused).
  NSString *cellReuseIdentifier;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  cellReuseIdentifier = @"cell";
}

-(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;
}

#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

      

शुरू करें

स्विफ़्ट पैकेज मैनेजर

iOS के लिए Maps SDK टूल को Swift Package Manager का इस्तेमाल करके इंस्टॉल किया जा सकता है.

  1. पक्का करें कि आपने iOS डिपेंडेंसी के लिए, Maps SDK टूल के सभी मौजूदा वर्शन हटा दिए हैं.
  2. टर्मिनल विंडो खोलें और tutorials/current-place-on-map डायरेक्ट्री पर जाएं.
  3. पक्का करें कि आपका Xcode फ़ाइल फ़ोल्डर बंद है और इन निर्देशों को चलाएं:
    sudo gem install cocoapods-deintegrate cocoapods-clean
    pod deintegrate
    pod cache clean --all
    rm Podfile
    rm current-place-on-map.xcworkspace
  4. अपना Xcode प्रोजेक्ट खोलें और पॉडफ़ाइल को मिटाएं.
  5. जगहें और Maps SDK टूल जोड़ें:
    1. फ़ाइल > पैकेज डिपेंडेंसी जोड़ें पर जाएं.
    2. यूआरएल के तौर पर, https://github.com/googlemaps/ios-places-sdk डालें. पैकेज पाने के लिए, Enter दबाएं और पैकेज जोड़ें पर क्लिक करें.
    3. यूआरएल के तौर पर, https://github.com/googlemaps/ios-maps-sdk डालें. पैकेज पाने के लिए, Enter दबाएं और पैकेज जोड़ें पर क्लिक करें.
  6. आपको फ़ाइल > पैकेज > पैकेज कैश मेमोरी रीसेट करें में जाकर, पैकेज की कैश मेमोरी को रीसेट करना पड़ सकता है.

CocoaPods का इस्तेमाल करना

  1. Xcode 14.0 वर्शन या इसके बाद का वर्शन डाउनलोड और इंस्टॉल करें.
  2. अगर आपके पास पहले से CocoaPods नहीं है, तो इसे macOS पर इंस्टॉल करें. इसके लिए, टर्मिनल से यह कमांड दें:
    sudo gem install cocoapods
  3. tutorials/current-place-on-map डायरेक्ट्री पर जाएं.
  4. pod install निर्देश चलाएं. इससे Podfile में बताए गए Maps और Places SDK टूल इंस्टॉल किए जाएंगे. साथ ही, यह भी अलग-अलग डिपेंडेंसी के तौर पर इंस्टॉल होगा.
  5. इंस्टॉल किए गए पॉड वर्शन की तुलना किसी भी नए अपडेट से करने के लिए, pod outdated चलाएं. अगर नए वर्शन का पता चलता है, तो Podfile को अपडेट करने के लिए pod update चलाएं और SDK टूल का नया वर्शन इंस्टॉल करें. ज़्यादा जानकारी के लिए, CocoaPods गाइड देखें.
  6. प्रोजेक्ट की current-place-on-map.xcworkspace फ़ाइल को Xcode में खोलने के लिए, उसे दो बार क्लिक करें. प्रोजेक्ट खोलने के लिए, आपको .xcworkspace फ़ाइल का इस्तेमाल करना होगा.

एपीआई पासकोड पाएं और ज़रूरी एपीआई चालू करें

इस ट्यूटोरियल को पूरा करने के लिए, आपको एक Google API कुंजी की ज़रूरत होगी जिसे iOS के लिए Maps SDK टूल और जगहें एपीआई इस्तेमाल करने की अनुमति हो.

  1. बिलिंग खाता और इन दोनों प्रॉडक्ट वाले प्रोजेक्ट को सेट अप करने के लिए, Google Maps Platform का इस्तेमाल शुरू करें में दिए गए निर्देशों का पालन करें.
  2. पहले सेट अप किए गए डेवलपमेंट प्रोजेक्ट के लिए एपीआई पासकोड बनाने के लिए, एपीआई पासकोड पाएं पर दिए गए निर्देशों का पालन करें.

अपने ऐप्लिकेशन में API कुंजी जोड़ें

अपने AppDelegate.swift में अपनी एपीआई कुंजी इस तरह जोड़ें:

  1. ध्यान दें कि फ़ाइल में यह इंपोर्ट स्टेटमेंट जोड़ दिया गया है:
    import GooglePlaces
    import GoogleMaps
  2. अपने application(_:didFinishLaunchingWithOptions:) तरीके में, यहां दी गई लाइन में बदलाव करें. इसमें YOUR_API_KEY को अपनी एपीआई कुंजी से बदलें:
    GMSPlacesClient.provideAPIKey("YOUR_API_KEY")
    GMSServices.provideAPIKey("YOUR_API_KEY")

अपना ऐप्लिकेशन बनाना और चलाना

  1. अपने कंप्यूटर से कोई iOS डिवाइस कनेक्ट करें या Xcode स्कीम पॉप-अप मेन्यू से, कोई सिम्युलेटर चुनें.
  2. अगर किसी डिवाइस का इस्तेमाल किया जा रहा है, तो पक्का करें कि जगह की जानकारी की सुविधा चालू हो. अगर सिम्युलेटर का इस्तेमाल किया जा रहा है, तो सुविधाएं मेन्यू में से कोई जगह चुनें.
  3. Xcode में, प्रॉडक्ट/रन मेन्यू विकल्प (या चलाएं बटन आइकॉन) पर क्लिक करें.
    • Xcode से ऐप्लिकेशन बनता है. इसके बाद, यह ऐप्लिकेशन को डिवाइस या सिम्युलेटर पर चलाता है.
    • आपको अपनी मौजूदा जगह के आस-पास कई मार्कर के साथ एक मैप दिखेगा.

समस्या का हल:

  • अगर आपको कोई मैप नहीं दिखता है, तो देखें कि आपने एपीआई पासकोड लिया हो और उसे ऐप्लिकेशन में जोड़ा हो. जैसा कि ऊपर बताया गया है. एपीआई पासकोड से जुड़ी गड़बड़ी के मैसेज के लिए, Xcode के डीबगिंग कंसोल पर जाएं.
  • अगर आपने iOS बंडल आइडेंटिफ़ायर की मदद से एपीआई पासकोड को सीमित किया है, तो ऐप्लिकेशन के लिए बंडल आइडेंटिफ़ायर जोड़ने के लिए, कुंजी में बदलाव करें: com.google.examples.current-place-on-map.
  • अगर जगह की जानकारी के लिए अनुमति का अनुरोध अस्वीकार किया जाता है, तो मैप ठीक से नहीं दिखेगा.
    • अगर किसी डिवाइस का इस्तेमाल किया जा रहा है, तो सेटिंग/सामान्य/निजता/जगह की जानकारी पर जाएं और जगह की जानकारी की सुविधा को फिर से चालू करें.
    • अगर सिम्युलेटर का इस्तेमाल किया जा रहा है, तो सिम्युलेटर/कॉन्टेंट रीसेट करें और सेटिंग... पर जाएं
    अगली बार ऐप्लिकेशन चलाने पर, जगह की जानकारी के अनुरोध को स्वीकार करना न भूलें.
  • पक्का करें कि आपका वाई-फ़ाई या जीपीएस कनेक्शन अच्छा हो.
  • अगर ऐप्लिकेशन लॉन्च हो जाता है, लेकिन कोई मैप नहीं दिखता है, तो पक्का करें कि आपने अपने प्रोजेक्ट के लिए Info.plist को सही जगह की अनुमतियों के साथ अपडेट किया हो. अनुमतियों को मैनेज करने के बारे में ज़्यादा जानकारी के लिए, अपने ऐप्लिकेशन में जगह की जानकारी की अनुमति का अनुरोध करने से जुड़ी गाइड नीचे दी गई है.
  • लॉग देखने और ऐप्लिकेशन को डीबग करने के लिए, Xcode डीबग करने वाले टूल का इस्तेमाल करें.

कोड को समझना

ट्यूटोरियल के इस हिस्से में, current-place-on-map ऐप्लिकेशन के सबसे अहम हिस्सों के बारे में बताया गया है. इससे आपको मिलता-जुलता ऐप्लिकेशन बनाने का तरीका समझने में मदद मिलेगी.

current-place-on-map' ऐप्लिकेशन में दो व्यू कंट्रोलर होते हैं: पहला, मैप पर उपयोगकर्ता की मौजूदा चुनी गई जगह को दिखाने के लिए और दूसरा, उपयोगकर्ता को उस जगह की सूची दिखाने के लिए जिसे उपयोगकर्ता ने चुना है. ध्यान दें कि हर व्यू कंट्रोलर में संभावित जगहों (likelyPlaces) की सूची को ट्रैक करने के लिए और उपयोगकर्ता के चुनाव (selectedPlace) को दिखाने के लिए एक ही वैरिएबल होते हैं. व्यू के बीच नेविगेशन करने के लिए segues का इस्तेमाल किया जाता है.

जगह की जानकारी की अनुमति का अनुरोध किया जा रहा है

आपके ऐप्लिकेशन को, लोगों से जगह की जानकारी का इस्तेमाल करने की सहमति लेने का प्रॉम्प्ट मैसेज भेजना होगा. इसके लिए, ऐप्लिकेशन की Info.plist फ़ाइल में NSLocationAlwaysUsageDescription कुंजी शामिल करें. साथ ही, हर कुंजी की वैल्यू को ऐसी स्ट्रिंग पर सेट करें जिससे पता चलता हो कि ऐप्लिकेशन जगह की जानकारी के डेटा का इस्तेमाल कैसे करता है.

स्थान मैनेजर सेट अप करना

डिवाइस की मौजूदा जगह की जानकारी पाने और डिवाइस के नई जगह पर शिफ़्ट होने पर, नियमित तौर पर अपडेट पाने का अनुरोध करने के लिए, 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. viewDidLoad() में लोकेशन मैनेजर और GMSPlacesClient शुरू करें.
  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;
      

उपयोगकर्ता से अपनी मौजूदा जगह चुनने का अनुरोध करना

iOS के लिए जगहें SDK टूल का इस्तेमाल करके, उपयोगकर्ता की मौजूदा जगह के आधार पर पांच मुख्य जगहों की संभावना पाएं. साथ ही, उस सूची को 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 को मौजूदा संभावित जगहों की सूची के साथ अपडेट करता है. साथ ही, कोई सेग किए जाने पर अपने-आप कॉल हो जाता है.
  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 मैप पर दिखाता है. इस काम के दौरान, आपने iOS के लिए Places SDK टूल, iOS के लिए Maps SDK, और Apple Core लोकेशन फ़्रेमवर्क को इस्तेमाल करना सीख लिया है.