程式碼研究室簡介
1. 事前準備
開始編寫程式碼之前,您必須設定一些先決條件。
Xcode
本教學課程使用 Apple 的 Xcode 工具以及 Objective-C 語言,建立可在模擬器中執行的簡易 iOS 應用程式。你不需要實體裝置。您可以前往 https://developer.apple.com/xcode/ 取得 Xcode
CocoaPods
Places SDK for iOS 可做為 CocoaPods pod。CocoaPods 是 Swift 和 Objective-C 專案的開放原始碼依附元件管理工具。如果您尚未安裝這項工具,請先進行安裝,再進行後續操作。您可以從終端機安裝,如下所示:
sudo gem install cocoapods
如要進一步瞭解 CocoaPods,請參閱 CocoaPods 入門指南。
安裝 SDK
如要安裝 SDK,您需要在專案目錄中建立 Podfile,讓 CocoaPods 用來下載和設定必要的依附元件。最簡單的方法是在 Xcode 中建立新專案,在其中新增 Podfile 並安裝 Pod。
開啟 [Xcode] 後,您會看到「歡迎使用 Xcode'」畫面。在這裡選取 [建立新的 Xcode 專案]
在下一個畫面中,系統會請您為新專案提供範本。選取 [單一檢視應用程式] (適用於 iOS 裝置),然後按下 [下一步]。
要求提供產品名稱時,您可以選擇任何所需的項目,但請記得記下系統產生的軟體包 ID。您稍後會用到。
按 [下一步],即可為您建立專案。記下建立目錄的目錄。關閉 Xcode 並使用終端機,前往該目錄。
使用終端機,輸入下列指令:
pod init
系統將為您建立名為 Podfile 的檔案。編輯以在 Google 地圖上新增 pod,如下所示:
target '{YOUR APP NAME}' do
pod 'GoogleMaps'
end
儲存並關閉 Xcode。請務必關閉專案,因為在下一個步驟中,您將要編輯基礎專案。完成之後,您必須打開一個不同的工程文件,這裡的設計人很常識到一切都像以前他們之前都不接近 Xcode!現在,在終端機中前往專案目錄,然後執行「pod install'」;範例如下:
完成後,系統就會安裝 pod 並建立新的 .xcworkspace 檔案。從現在起,請為專案套用這項設定。不過在編寫程式碼之前,接下來您就需要提供 API 金鑰。
2. 取得 API 金鑰
在下列啟用步驟中,啟用 Maps SDK for iOS。
設定 Google 地圖平台
如果您還沒有 Google Cloud Platform 帳戶和已啟用計費功能的專案,請參閱開始使用 Google 地圖平台指南,建立帳單帳戶和專案。
- 在 Cloud Console 中按一下專案下拉式選單,然後選取您要用於這個程式碼研究室的專案。
3. 建立 Places API 應用程式
現在您已經建立了主控台專案,並已為其啟用 Places API,並取得 API 金鑰後,就可以開始編寫第一個 Places API 應用程式。
安裝 pod 檔案之前,系統已為您建立新的 .xcworkspace 檔案。按兩下即可開啟。
您會在「專案多層檢視」中發現,您現已建立了名為「Pods'」的新資料夾。如果成功,您就會看到內含架構的 GoogleMaps 資料夾。
4. 編輯 Info.plist 檔案。
首次執行應用程式時,iOS 會顯示一個對話方塊,要求使用者授予定位服務的存取權限。這個對話方塊會提供您定義的字串,並將其放在 Info.plist 檔案中。如果這個字串不存在,此對話方塊並不會顯示,應用程式也無法繼續運作。
您可以在 Project Explorer 中找到 Info.plist 檔案,網址如下:
只要選取該標籤,系統就會列出 plist 編輯器。
將滑鼠移到任何元素上,您就會看見「+'」圖示。按下該按鈕後,您就會看到新的項目。在這個方塊中,輸入「NSLocationAlwaysUsageDescription'」值。
按下 Enter 鍵即可新增按鍵。接著按兩下此鍵值的「值」欄,並新增一個字串:
如要進一步瞭解這個字串,請參閱 Apple 開發人員說明文件。
5. 編輯應用程式委派
在專案多層檢視中,找出並開啟 AppDelegate.m 以開啟 API 金鑰。
請在檔案頂端的 ## 行下方加入以下內容:
@import GoogleMaps;
然後在 doFinishLaunchingWithOptions: 函式中,加入有關「return YES' line:」的指令。
[GMSServices provideAPIKey:@"<Add your API Key>"];
請務必使用您之前產生的 API 金鑰。
6. 編輯您的分鏡腳本檔案
在專案多層檢視中,開啟 Main.storyboard 檔案。按下右上角的側欄按鈕,確定側欄已啟用。
接著,在側欄底部選取 [Object Library] (物件庫),即可找到標籤控制項。
在左側的「View Controller Scene」中,確認已選取「View'」:
然後將 7 個標籤拖曳到檢視畫面中。請按照這裡的說明排列。請務必拖曳廣告素材的大小,以符合顯示內容。如要編輯標籤中的文字,請按兩下文字,然後輸入必要值:
針對最底層的標籤 (真的大標籤),請前往屬性編輯器,確定它設定為 0 行 (預設值為 1)。這將允許顯示多行。
7. 為值建立插座
對於 3“值'標籤,您需要建立一個插座。如此一來,您就能使用程式碼變更其值。如果要這麼做,必須先啟用助理編輯器。做法是先按一下屬性側欄的 [移除] 按鈕,即可予以移除。(這個按鈕顯示在上一個步驟中)
然後,選取助理按鈕,這裡就是雙圓圈的圓圈:
請確定該檔案可以顯示 ViewController.h 檔案。如果不支援,你可以使用助理視窗頂端的編輯器來變更設定。
然後,按住 CONTROL 鍵後,將每個標籤拖放至助理中 ViewController.h 檔案的 @face 行下方。系統會顯示一個對話方塊,詢問您要建立的連線類型:
請確認設定如下所示 (連線:插座;類型:UILabel;儲存空間:低),然後為各個項目命名。就本程式碼研究室而言,我分別將「經度」、「緯度」、「高度」標籤分別稱為「lblLongitude」、「lblLatitude」和「lblAltidude」。也可以從底部拖曳大型標籤,並將其命名為 lblPlaces。
完成後,ViewController.h 檔案應該會如下所示:
#import <UIKit/UIKit.h>
@import GoogleMaps;
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *lblLatitude;
@property (weak, nonatomic) IBOutlet UILabel *lblLongitude;
@property (weak, nonatomic) IBOutlet UILabel *lblAltitude;
@property (weak, nonatomic) IBOutlet UILabel *lblPlaces;
@end
8. 編輯 Location 和 Google Client API 的標頭檔案
在最後一個步驟 (您必須建置使用 Places API 的應用程式) 中,您必須在標頭檔案 (ViewController.h) 中再設定幾個變數。以下是核心位置管理員和核心位置物件:
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) CLLocation *location;
您還需要 Google API 用戶端:
@property GMSPlacesClient *placesClient;
最後,您必須更新標頭檔案,讓類別實作 CLLocationManagerDelegate:
@interface ViewController : UIViewController<CLLocationManagerDelegate>
完成後,您的標頭檔案看起來應該會像這樣:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <GoogleMaps/GoogleMaps.h>
@interface ViewController : UIViewController<CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) CLLocation *location;
@property (weak, nonatomic) IBOutlet UILabel *lblLongitude;
@property (weak, nonatomic) IBOutlet UILabel *lblLatitude;
@property (weak, nonatomic) IBOutlet UILabel *lblAltitude;
@property (weak, nonatomic) IBOutlet UILabel *lblPlaces;
@property GMSPlacesClient *placesClient;
@end
9. 編輯您的資料檢視控制器
第一個步驟是編輯 view 最多載入函式,以初始化位置管理員,並要求使用者授權存取位置資訊,最後再啟動位置管理員,讓它能夠追蹤目前的位置。您也會初始化 Google Places API 用戶端。
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
// Or [self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
self.locationManager.delegate = self;
self.location = [[CLLocation alloc] init];
self.placesClient = [GMSPlacesClient sharedClient];
}
10. 處理位置更新
「位置管理員」會呼叫 doUpdateLocations 函式,將您傳回的位置更新與「檢視控制器」一併傳回。你必須把它新增到 ViewController.m。此函式看起來像這樣:
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
// Enter code here
}
這個函式需要執行一些動作。
首先,它會快取最近收到的位置。
self.location = locations.lastObject;
接著,請更新「Google 定位」、「經度」和「高度」這 3 個標籤:
self.lblLatitude.text = [NSString stringWithFormat:@"%f", self.location.coordinate.latitude];
self.lblLongitude.text = [NSString stringWithFormat:@"%f", self.location.coordinate.longitude];
self.lblAltitude.text = [NSString stringWithFormat:@"%f", self.location.altitude];
接下來,請使用 Places Client 呼叫 Places API。只要指定回呼函式,即可取得可能性清單。Places API 會根據您的位置,判斷您位於特定地點的可能性。它會傳回可能位置的名稱,以及介於 0 和 1 之間的值,其中包含您在該位置的機率。
[self.placesClient currentPlaceWithCallback:^(GMSPlaceLikelihoodList *likelihoodList, NSError *error) {
然後就可以執行回呼。系統就會反覆瀏覽可能性清單,為這些地點新增地點和可能性。
[self.placesClient currentPlaceWithCallback:^(GMSPlaceLikelihoodList *likelihoodList, NSError *error) {
if (error != nil) {
NSLog(@"Current Place error %@", [error localizedDescription]);
return;
}
NSMutableString *strPlaces = [NSMutableString stringWithString:@""];
for (GMSPlaceLikelihood *likelihood in likelihoodList.likelihoods) {
GMSPlace* place = likelihood.place;
NSLog(@"Current Place name %@ at likelihood %g", place.name,
likelihood.likelihood);
NSLog(@"Current Place address %@", place.formattedAddress);
NSLog(@"Current Place attributions %@", place.attributions);
NSLog(@"Current PlaceID %@", place.placeID);
[strPlaces appendString:place.name];
[strPlaces appendString:@" "];
[strPlaces appendFormat:@"%g",likelihood.likelihood];
[strPlaces appendString:@"\n"];
}
self.lblPlaces.text = strPlaces;
}];
完成後,已完成的 UpdateLocations 函式應如下所示:
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
self.location = locations.lastObject;
self.lblLatitude.text = [NSString stringWithFormat:@"%f", self.location.coordinate.latitude];
self.lblLongitude.text = [NSString stringWithFormat:@"%f", self.location.coordinate.longitude];
self.lblAltitude.text = [NSString stringWithFormat:@"%f", self.location.altitude];
NSLog(@"%@", self.location.description);
[self.placesClient currentPlaceWithCallback:^(GMSPlaceLikelihoodList *likelihoodList, NSError *error) {
if (error != nil) {
NSLog(@"Current Place error %@", [error localizedDescription]);
return;
}
NSMutableString *strPlaces = [NSMutableString stringWithString:@""];
for (GMSPlaceLikelihood *likelihood in likelihoodList.likelihoods)
{
GMSPlace* place = likelihood.place;
NSLog(@"Current Place name %@ at likelihood %g", place.name, likelihood.likelihood);
NSLog(@"Current Place address %@", place.formattedAddress);
NSLog(@"Current Place attributions %@", place.attributions);
NSLog(@"Current PlaceID %@", place.placeID);
[strPlaces appendString:place.name];
[strPlaces appendString:@" "];
[strPlaces appendFormat:@"%g",likelihood.likelihood];
[strPlaces appendString:@"\n"];
}
self.lblPlaces.text = strPlaces;
}];
}
現在,你可以開始執行並測試應用程式了!
11. 在模擬器中執行應用程式
應用程式標題列上的 [執行] 按鈕可用來執行應用程式。這也可讓您選取執行類型。如此處所見,我使用模擬器在 iPhone 6 上進行測試。
按下執行按鈕後,應用程式即會啟動並啟動。系統隨即顯示允許應用程式存取位置資訊的要求,包括您之前指定的自訂字串。
如此一來,「Google 定位」和「經度」就會進行更新。如要變更位置,請選取 [偵錯] 選單,然後選擇位置。例如,您可以挑選「高速公路公路」
如此一來,您就能查看可能更新的地點,模擬高速公路車道。
這樣就完成了!您已成功在 iOS 版 Google Places API 中存取目前地點詳細資料。