[swift] Google MAP API for iOSを実装する方法まとめ
目次
Google MAP API for iOSを実装
podインストール
下記podをpodファイルに追記し、podインストール
pod 'GoogleMaps'
*podインストールは下記参照
[objective-c] podを使用してライブラリをインストールする方法
Google Developer Consoleにログイン
https://console.developers.google.com/
新しいGoogleプロジェクト
Google Developer Consoleで新しいxcodeプロジェクトを作成
Google MAP API for iOS有効
Google MAP API for iOSを選択→有効
キー作成
認証画面になるので、キーを作成
キー名は適当に、バンドル名はアプリのバンドル名を追加
APIキーが払い出されるので、コピー
サンプルコード:AppDelegate
import UIKit
import GoogleMaps; //追記
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let cGoogleMapsAPIKey = "Googleで取得したAPIKey" //追記
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
GMSServices.provideAPIKey(cGoogleMapsAPIKey) //追記
return true
}
}
サンプルコード:ViewController
import Foundation
import GoogleMaps
class homeViewController: UIViewController {
var googleMap : GMSMapView!
//緯度経度 -> 有楽町
let latitude: CLLocationDegrees = 35.6824745
let longitude: CLLocationDegrees = 139.755561
//緯度経度 -> 東京駅
let latitude2: CLLocationDegrees = 35.681298
let longitude2: CLLocationDegrees = 139.766247
override func viewDidLoad() {
super.viewDidLoad()
let width = self.view.frame.maxX
let height = self.view.frame.maxY
// ズームレベル.
let zoom: Float = 15
// カメラを生成.
let camera: GMSCameraPosition = GMSCameraPosition.cameraWithLatitude(latitude,longitude: longitude, zoom: zoom)
// MapViewを生成.
googleMap = GMSMapView(frame: CGRectMake(0, 0, width, height))
// MapViewにカメラを追加.
googleMap.camera = camera
//マーカーの作成
let marker: GMSMarker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(latitude, longitude)
marker.icon = GMSMarker.markerImageWithColor(UIColor.blueColor()) //マーカーの色を青に
marker.opacity = 0.6 //マーカーの透明度を0.6に
marker.map = googleMap
//もう1個マーカー作成
let othermarker: GMSMarker = GMSMarker()
othermarker.position = CLLocationCoordinate2DMake(latitude2, longitude2)
othermarker.title = "London";
othermarker.snippet = "Population: 8,174,100"
othermarker.icon = UIImage(named: "house.png") //マーカーを画像に
othermarker.opacity = 0.1 //マーカーの透明度を0.6に
othermarker.map = googleMap
//もう1個のマーカー周辺に薄い青の円を描画
let circleCenter = CLLocationCoordinate2DMake(latitude2, longitude2);
let circ = GMSCircle(position: circleCenter, radius: 1000) //半径1000メートルの円
circ.fillColor = UIColor(red: 0, green: 0, blue: 0.35, alpha: 0.2)
circ.strokeColor = UIColor.blueColor()
circ.map = googleMap;
let path = GMSMutablePath() //線の準備
path.addCoordinate(CLLocationCoordinate2DMake(latitude, longitude)) //有楽町から
path.addCoordinate(CLLocationCoordinate2DMake(latitude2, longitude2)) //東京駅まで
let polyline = GMSPolyline(path: path) //線を作成
polyline.strokeWidth = 3.0//線の太さ
polyline.map = googleMap//線を描画
//viewにMapViewを追加.
self.view.addSubview(googleMap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}