質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Google マップ

Google Mapは、Google社がオンラインで提供している地図・ローカル検索サービスです。GIS(Geographic Information System:地理情報システム)の中の「WebGIS」に該当します。地図・航空写真・地形の表示方式があり、それぞれユーザーが縮尺を調整して表示させることができます。地域の情報サービスを検索する機能やルート検索の機能も搭載されています。

Q&A

解決済

1回答

751閲覧

初回のみGoogle Mapが表示されない

shihominorth

総合スコア46

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Google マップ

Google Mapは、Google社がオンラインで提供している地図・ローカル検索サービスです。GIS(Geographic Information System:地理情報システム)の中の「WebGIS」に該当します。地図・航空写真・地形の表示方式があり、それぞれユーザーが縮尺を調整して表示させることができます。地域の情報サービスを検索する機能やルート検索の機能も搭載されています。

0グッド

0クリップ

投稿2022/03/16 03:40

前提・実現したいこと

Google Mapを表示したい。

発生している問題・エラーメッセージ

<br>

Google MapをiOSアプリ上にアプリをインストールして初めて表示するとき、権限を許可した後Googleマップが表示できない。(前のVCに一旦戻り、2回目以降はマップを表示できる)

Mapが表示される一個まえのView Controller

左上のハンバーガーメニューを開いた後、Google Mapを表示するView Controllerに変遷できる選択肢(Tavble view cell)があるのでそこをタップ

権限をユーザーに聞く

許可してるのに何も表示されない状態になる。

Map

<br>

該当のソースコード

Swift

1 2import UIKit 3import CoreLocation 4import GoogleMaps 5import GooglePlaces 6 7 8class MapViewController: UIViewController { 9 10 private var mapView: GMSMapView! 11 12 private let locationManager = CLLocationManager() 13 14 override func viewDidLoad() { 15 16 super.viewDidLoad() 17 18 19 guard let apiKey = KeyManager().getValue(key:"Google Maps API Key") else { 20 return 21 } 22 23 24 GMSServices.provideAPIKey(apiKey) 25 GMSPlacesClient.provideAPIKey(apiKey) 26 27 locationManager.delegate = self 28 locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 29 30 if CLLocationManager.locationServicesEnabled() { 31 32 switch (CLLocationManager.authorizationStatus()) { 33 34 case .notDetermined, .restricted, .denied: 35 print("No access") 36 37 case .authorizedAlways, .authorizedWhenInUse: 38 print("Access") 39 40 default: 41 break 42 43 } 44 45 46 } else { 47 48 print("Location services are not enabled") 49 50 } 51 52 if CLLocationManager.authorizationStatus() == .authorizedAlways || CLLocationManager.authorizationStatus() == .authorizedWhenInUse { 53 54 locationManager.startUpdatingLocation() 55 56 57 let camera = GMSCameraPosition.camera(withLatitude: locationManager.location!.coordinate.latitude, longitude: locationManager.location!.coordinate.longitude, zoom: 15); 58 59 mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera) 60 mapView.delegate = self 61 mapView.settings.myLocationButton = true 62 mapView.isMyLocationEnabled = true 63 64 65 self.view.addSubview(mapView) 66 67 68 mapView.translatesAutoresizingMaskIntoConstraints = false 69 70 NSLayoutConstraint.activate([ 71 mapView.topAnchor.constraint(equalTo: view.topAnchor), 72 mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor), 73 mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor), 74 mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor) 75 ]) 76 77 getCafeImformation() 78 79 } else { 80 81 print("Location services are not enabled") 82 83 } 84 85 86 87 } 88 89 private func getCafeImformation() { 90 91 let session = URLSession.shared 92 93 guard let apiKey = KeyManager().getValue(key:"Google Maps API Key") else { 94 return 95 } 96 97 98 99 guard let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(locationManager.location!.coordinate.latitude),\(locationManager.location!.coordinate.longitude)&radius=4500&type=cafe&key=\(String(describing: apiKey))") 100 else { 101 return 102 } 103 104 print(url.absoluteString) 105 106 let task = session.dataTask(with: url) { data, response, error in 107 108 109 if let error = error { 110 111 print(error) 112 113 if data == nil { 114 print("Client error!") 115 return 116 } 117 } 118 else { 119 120 121 guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else { 122 print("Server error!") 123 return 124 } 125 126 guard let mime = response.mimeType, mime == "application/json" else { 127 print("Wrong MIME type!") 128 return 129 } 130 131 do { 132 let json = try JSONSerialization.jsonObject(with: data!, options: []) 133 print(json) 134 } catch { 135 print("JSON error: \(error.localizedDescription)") 136 } 137 138 do { 139 let decoder = JSONDecoder() 140 decoder.keyDecodingStrategy = .convertFromSnakeCase 141 let root = try decoder.decode(Root.self, from: data!) 142 print(root) 143 144 self.root = root 145 self.createMarkers() 146 147 } catch (let err) { 148 149 print(err) 150 151 } 152 153 } 154 } 155 156 157 158 task.resume() 159 160 161 } 162 163 <!-- <省略> --> 164} 165 166 <!-- <省略> --> 167 168extension MapViewController: CLLocationManagerDelegate { 169 170 func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { 171 172 guard status == .authorizedWhenInUse || status == .authorizedAlways else { 173 return 174 } 175 176 locationManager.startUpdatingLocation() 177 178 179 let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first 180 181 if var topController = keyWindow?.rootViewController { 182 183 while let presentedViewController = topController.presentedViewController { 184 185 topController = presentedViewController 186 187 } 188 189 guard topController is MapViewController else { 190 191 mapView?.isMyLocationEnabled = true 192 mapView?.settings.myLocationButton = true 193 194 //MARK: 後ほど解説。もう一回View controllerを更新しようとしています。 195 <!-- self.loadView() 196 self.viewDidLoad() --> 197 198 return 199 } 200 201 } 202 203 204 205 } 206 207 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 208 209 guard let location = locations.first else { 210 return 211 } 212 213 locationManager.stopUpdatingLocation() 214 215 216 217 } 218} 219 220 221

試したこと

  • もう一度View Controllerを更新。ただこれをすると今度は一個前のView ControllerもGoogle Mapを表示してしまう。

    • func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus)ないにView Controllerを更新しているところが記載されています。
    • できればCore Data, UserDefaultsを使わずに問題を解決してみたい。

補足情報(FW/ツールのバージョンなど)

Xcode 13.2.1

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hoshi-takanori

2022/03/16 03:48

didChangeAuthorization で viewDidLoad を呼んでますが、これは良くないですね。 viewDidLoad の中のマップ生成部分をメソッドに切り出して、それを呼ぶべきかと。(それで直るかは分かりませんが…。)
guest

回答1

0

自己解決

シンプルに func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus)内で、statusが.authorizedWhenInUseか.authorizedAlwaysの時にマップを生成するfunctionを呼ぶだけでした。凡ミスでした.. アドバイスいただいたhoshi takanoriさんありがとうございました!

投稿2022/03/16 04:28

shihominorth

総合スコア46

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問