বর্তমান স্থান নির্বাচন করুন এবং মানচিত্রে বিশদ বিবরণ দেখান

এই টিউটোরিয়ালটি এমন একটি iOS অ্যাপ তৈরির পদ্ধতি প্রদর্শন করে যা ডিভাইসের বর্তমান অবস্থান উদ্ধার করে, সম্ভাব্য অবস্থানগুলি সনাক্ত করে, ব্যবহারকারীকে সেরা মিলটি নির্বাচন করতে অনুরোধ করে এবং নির্বাচিত অবস্থানের জন্য একটি মানচিত্র চিহ্নিতকারী প্রদর্শন করে।

এটি তাদের জন্য উপযুক্ত যাদের Swift বা Objective-C এর প্রাথমিক বা মধ্যবর্তী জ্ঞান এবং Xcode এর সাধারণ জ্ঞান রয়েছে। মানচিত্র তৈরির জন্য উন্নত নির্দেশিকার জন্য, ডেভেলপারদের নির্দেশিকাটি পড়ুন।

এই টিউটোরিয়ালটি ব্যবহার করে আপনি নিম্নলিখিত মানচিত্রটি তৈরি করবেন। মানচিত্র চিহ্নিতকারীটি ক্যালিফোর্নিয়ার সান ফ্রান্সিসকোতে অবস্থিত, তবে ডিভাইস বা সিমুলেটর যেখানেই অবস্থিত সেখানেই স্থানান্তরিত হবে।

এই টিউটোরিয়ালটি iOS এর জন্য Places SDK , iOS এর জন্য Maps SDK এবং Apple Core Location ফ্রেমওয়ার্ক ব্যবহার করে।

কোডটি পান

GitHub থেকে Google Maps iOS নমুনা সংগ্রহস্থল ক্লোন করুন অথবা ডাউনলোড করুন।

অথবা, সোর্স কোড ডাউনলোড করতে নিম্নলিখিত বোতামে ক্লিক করুন:

কোডটা দাও।

ম্যাপভিউকন্ট্রোলার

সুইফট

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

অবজেক্টিভ-সি

#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
      

প্লেসভিউকন্ট্রোলার

সুইফট

import UIKit
import GooglePlaces

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

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

অবজেক্টিভ-সি

#import "PlacesViewController.h"

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

#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. স্থান এবং মানচিত্র SDK যোগ করুন:
    1. ফাইল > প্যাকেজ নির্ভরতা যোগ করুন এ যান।
    2. URL হিসেবে https://github.com/googlemaps/ios-places-sdk লিখুন, প্যাকেজটি টেনে আনতে Enter টিপুন এবং Add Package এ ক্লিক করুন।
    3. URL হিসেবে https://github.com/googlemaps/ios-maps-sdk লিখুন, প্যাকেজটি টেনে আনতে Enter টিপুন এবং Add Package এ ক্লিক করুন।
  6. আপনার প্যাকেজ ক্যাশে File > Packages > Reset Package Cache ব্যবহার করে রিসেট করতে হতে পারে।

কোকোপডস ব্যবহার করুন

  1. Xcode সংস্করণ 16.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 আপডেট করতে এবং সর্বশেষ SDK ইনস্টল করতে pod update চালান। আরও বিস্তারিত জানার জন্য, CocoaPods গাইড দেখুন।
  6. Xcode-এ খুলতে প্রকল্পের current-place-on-map.xcworkspace ফাইলটি খুলুন (ডাবল-ক্লিক করুন)। প্রকল্পটি খুলতে আপনাকে .xcworkspace ফাইলটি ব্যবহার করতে হবে।

একটি API কী পান এবং প্রয়োজনীয় API গুলি সক্ষম করুন

এই টিউটোরিয়ালটি সম্পূর্ণ করার জন্য, আপনার একটি Google API কী প্রয়োজন যা iOS এর জন্য Maps SDK এবং Places API ব্যবহারের জন্য অনুমোদিত।

  1. এই দুটি পণ্যের সাথে একটি বিলিং অ্যাকাউন্ট এবং একটি প্রকল্প সক্ষম করতে Google Maps প্ল্যাটফর্মের সাথে শুরু করুন- এর নির্দেশাবলী অনুসরণ করুন।
  2. আপনার পূর্বে সেট আপ করা ডেভেলপমেন্ট প্রকল্পের জন্য একটি API কী তৈরি করতে Get an API Key- এর নির্দেশাবলী অনুসরণ করুন।

আপনার অ্যাপ্লিকেশনে API কী যোগ করুন

আপনার AppDelegate.swift এ আপনার API কীটি নিম্নরূপ যোগ করুন:

  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 মেনু অপশনে (অথবা play button আইকনে) ক্লিক করুন।
    • এক্সকোড অ্যাপটি তৈরি করে, এবং তারপর ডিভাইসে বা সিমুলেটরে অ্যাপটি চালায়।
    • আপনার বর্তমান অবস্থানের চারপাশে কেন্দ্রীভূত বেশ কয়েকটি মার্কার সহ একটি মানচিত্র দেখতে পাবেন।

সমস্যা সমাধান:

  • যদি আপনি কোন মানচিত্র দেখতে না পান, তাহলে উপরে বর্ণিত পদ্ধতিতে আপনি একটি API কী পেয়েছেন এবং অ্যাপে এটি যোগ করেছেন কিনা তা পরীক্ষা করে দেখুন। API কী সম্পর্কে ত্রুটির বার্তাগুলির জন্য Xcode এর ডিবাগিং কনসোলটি পরীক্ষা করুন।
  • যদি আপনি iOS বান্ডেল আইডেন্টিফায়ার দ্বারা API কী সীমাবদ্ধ করে থাকেন, তাহলে অ্যাপের জন্য বান্ডেল আইডেন্টিফায়ার যোগ করতে কীটি সম্পাদনা করুন: com.google.examples.current-place-on-map
  • লোকেশন পরিষেবার অনুমতির অনুরোধ প্রত্যাখ্যান করা হলে মানচিত্রটি সঠিকভাবে প্রদর্শিত হবে না।
    • আপনি যদি কোনও ডিভাইস ব্যবহার করেন, তাহলে সেটিংস/সাধারণ/গোপনীয়তা/অবস্থান পরিষেবাগুলিতে যান এবং অবস্থান পরিষেবাগুলি পুনরায় সক্ষম করুন।
    • যদি আপনি একটি সিমুলেটর ব্যবহার করেন, তাহলে সিমুলেটর/রিসেট কন্টেন্ট এবং সেটিংস... এ যান।
    পরের বার অ্যাপটি চালানোর সময়, লোকেশন সার্ভিস প্রম্পট গ্রহণ করতে ভুলবেন না।
  • নিশ্চিত করুন যে আপনার একটি ভালো Wi-Fi অথবা GPS সংযোগ আছে।
  • যদি অ্যাপটি চালু হয় কিন্তু কোনও মানচিত্র প্রদর্শিত না হয়, তাহলে নিশ্চিত করুন যে আপনি আপনার প্রকল্পের জন্য উপযুক্ত অবস্থানের অনুমতি সহ Info.plist আপডেট করেছেন। অনুমতি পরিচালনা সম্পর্কে আরও তথ্যের জন্য, নীচে আপনার অ্যাপে অবস্থানের অনুমতি অনুরোধ করার নির্দেশিকাটি দেখুন।
  • লগ দেখতে এবং অ্যাপটি ডিবাগ করতে Xcode ডিবাগিং টুল ব্যবহার করুন।

কোডটি বুঝুন

টিউটোরিয়ালের এই অংশে বর্তমান-স্থান-অন-ম্যাপ অ্যাপের সবচেয়ে গুরুত্বপূর্ণ অংশগুলি ব্যাখ্যা করা হয়েছে, যাতে আপনি বুঝতে পারেন কিভাবে একই ধরণের অ্যাপ তৈরি করতে হয়।

current-place-on-map অ্যাপটিতে দুটি ভিউ কন্ট্রোলার রয়েছে: একটি ব্যবহারকারীর নির্বাচিত স্থান দেখানোর জন্য একটি মানচিত্র প্রদর্শন করার জন্য এবং অন্যটি ব্যবহারকারীকে সম্ভাব্য স্থানগুলির তালিকা উপস্থাপন করার জন্য। মনে রাখবেন যে প্রতিটি ভিউ কন্ট্রোলারের সম্ভাব্য স্থানগুলির তালিকা ট্র্যাক করার জন্য ( likelyPlaces ) এবং ব্যবহারকারীর নির্বাচন নির্দেশ করার জন্য ( selectedPlace ) একই ভেরিয়েবল রয়েছে। segues ব্যবহার করে ভিউগুলির মধ্যে নেভিগেশন সম্পন্ন করা হয়।

অবস্থানের অনুমতির অনুরোধ করা হচ্ছে

আপনার অ্যাপটি ব্যবহারকারীর কাছ থেকে লোকেশন পরিষেবা ব্যবহারের সম্মতি চাইতে হবে। এটি করার জন্য, অ্যাপের Info.plist ফাইলে NSLocationAlwaysUsageDescription কী অন্তর্ভুক্ত করুন এবং প্রতিটি কী-এর মান একটি স্ট্রিংয়ে সেট করুন যা বর্ণনা করে যে অ্যাপটি কীভাবে লোকেশন ডেটা ব্যবহার করতে চায়।

লোকেশন ম্যানেজার সেট আপ করুন

ডিভাইসের বর্তমান অবস্থান খুঁজে পেতে এবং ডিভাইসটি নতুন স্থানে স্থানান্তরিত হলে নিয়মিত আপডেটের অনুরোধ করতে CLLocationManager ব্যবহার করুন। এই টিউটোরিয়ালে ডিভাইসের অবস্থান জানতে আপনার প্রয়োজনীয় কোডটি প্রদান করা হয়েছে। আরও বিস্তারিত জানার জন্য, অ্যাপল ডেভেলপার ডকুমেন্টেশনে ব্যবহারকারীর অবস্থান সম্পর্কে নির্দেশিকাটি দেখুন।

  1. ক্লাস লেভেলে লোকেশন ম্যানেজার, বর্তমান লোকেশন, ম্যাপ ভিউ, প্লেস ক্লায়েন্ট এবং ডিফল্ট জুম লেভেল ঘোষণা করুন।
  2. সুইফট

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

    অবজেক্টিভ-সি

    CLLocationManager *locationManager;
    CLLocation * _Nullable currentLocation;
    GMSMapView *mapView;
    GMSPlacesClient *placesClient;
    float preciseLocationZoomLevel;
    float approximateLocationZoomLevel;
          
  3. viewDidLoad() তে লোকেশন ম্যানেজার এবং GMSPlacesClient আরম্ভ করুন।
  4. সুইফট

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

    অবজেক্টিভ-সি

    // 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. সুইফট

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

    অবজেক্টিভ-সি

    // An array to hold the list of likely places.
    NSMutableArray<GMSPlace *> *likelyPlaces;
    
    // The currently selected place.
    GMSPlace * _Nullable selectedPlace;
          
  7. একটি এক্সটেনশন ক্লজ ব্যবহার করে লোকেশন ম্যানেজারের ইভেন্ট পরিচালনা করার জন্য ডেলিগেট যোগ করুন।
  8. সুইফট

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

    অবজেক্টিভ-সি

    // 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 এক্সটেনশনে পরিচালনা করা হয়)।

সুইফট

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

অবজেক্টিভ-সি

// 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 এর জন্য Places SDK ব্যবহার করুন এবং তালিকাটি UITableView এ উপস্থাপন করুন। ব্যবহারকারী যখন একটি স্থান নির্বাচন করেন, তখন মানচিত্রে একটি মার্কার যোগ করুন।

  1. UITableView তৈরি করার সম্ভাব্য স্থানগুলির একটি তালিকা পান, যেখান থেকে ব্যবহারকারী তাদের অবস্থান নির্বাচন করতে পারবেন।
  2. সুইফট

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

    অবজেক্টিভ-সি

    // 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. সুইফট

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

    অবজেক্টিভ-সি

    // 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. সুইফট

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

    অবজেক্টিভ-সি

    #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. সুইফট

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

    অবজেক্টিভ-সি

    @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 স্বয়ংক্রিয়ভাবে কল করা হয়।

সুইফট

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

অবজেক্টিভ-সি

// 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 Location ফ্রেমওয়ার্ক ব্যবহার করতে শিখেছেন।