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

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

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

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

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

Q&A

解決済

1回答

936閲覧

hread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

BichaSoken

総合スコア13

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

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

0グッド

0クリップ

投稿2020/02/13 14:29

編集2020/02/13 15:39

調べたところ、このエラーの考えうるものとして、ui部品のoutketの関連づけが出来ていないと思ったのですが、一度閉じて再度開いても関連づけはしっかり出来ていました。

このコードのどこがダメなのでしょうか?

import UIKit import GoogleMaps import GooglePlaces import SwiftyJSON import Alamofire enum Location { case startLocation case destinationLocation } class ViewController: UIViewController , GMSMapViewDelegate , CLLocationManagerDelegate { var googleMaps: GMSMapView! @IBOutlet weak var startLocation: UITextField! @IBOutlet weak var destinationLocation: UITextField! var locationManager = CLLocationManager() var locationSelected = Location.startLocation var locationStart = CLLocation() var locationEnd = CLLocation() override func viewDidLoad() { super.viewDidLoad() locationManager = CLLocationManager() locationManager.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startMonitoringSignificantLocationChanges() //Your map initiation code let camera = GMSCameraPosition.camera(withLatitude: -7.9293122, longitude: 112.5879156, zoom: 15.0) エラー!!!!! self.googleMaps.camera = camera self.googleMaps.delegate = self self.googleMaps?.isMyLocationEnabled = true self.googleMaps.settings.myLocationButton = true self.googleMaps.settings.compassButton = true self.googleMaps.settings.zoomGestures = true } // MARK: function for create a marker pin on map func createMarker(titleMarker: String, iconMarker: UIImage, latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let marker = GMSMarker() marker.position = CLLocationCoordinate2DMake(latitude, longitude) marker.title = titleMarker marker.icon = iconMarker marker.map = googleMaps } //MARK: - Location Manager delegates func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Error to get location : (error)") } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last // let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 17.0) let locationTujuan = CLLocation(latitude: 37.784023631590777, longitude: -122.40486681461333) createMarker(titleMarker: "Lokasi Tujuan", iconMarker: #imageLiteral(resourceName: "mapspin") , latitude: locationTujuan.coordinate.latitude, longitude: locationTujuan.coordinate.longitude) createMarker(titleMarker: "Lokasi Aku", iconMarker: #imageLiteral(resourceName: "mapspin") , latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!) drawPath(startLocation: location!, endLocation: locationTujuan) // self.googleMaps?.animate(to: camera) self.locationManager.stopUpdatingLocation() } // MARK: - GMSMapViewDelegate func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) { googleMaps.isMyLocationEnabled = true } func mapView(_ mapView: GMSMapView, willMove gesture: Bool) { googleMaps.isMyLocationEnabled = true if (gesture) { mapView.selectedMarker = nil } } func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { googleMaps.isMyLocationEnabled = true return false } func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) { print("COORDINATE (coordinate)") // when you tapped coordinate } func didTapMyLocationButton(for mapView: GMSMapView) -> Bool { googleMaps.isMyLocationEnabled = true googleMaps.selectedMarker = nil return false } //MARK: - this is function for create direction path, from start location to desination location func drawPath(startLocation: CLLocation, endLocation: CLLocation) { let origin = "(startLocation.coordinate.latitude),(startLocation.coordinate.longitude)" let destination = "(endLocation.coordinate.latitude),(endLocation.coordinate.longitude)" let url = "https://maps.googleapis.com/maps/api/directions/json?origin=(origin)&destination=(destination)&mode=driving" Alamofire.request(url).responseJSON { response in print(response.request as Any) // original URL request print(response.response as Any) // HTTP URL response print(response.data as Any) // server data print(response.result as Any) // result of response serialization let json = try! JSON(data: response.data!) let routes = json["routes"].arrayValue // print route using Polyline for route in routes { let routeOverviewPolyline = route["overview_polyline"].dictionary let points = routeOverviewPolyline?["points"]?.stringValue let path = GMSPath.init(fromEncodedPath: points!) let polyline = GMSPolyline.init(path: path) polyline.strokeWidth = 4 polyline.strokeColor = UIColor.red polyline.map = self.googleMaps } } } // MARK: when start location tap, this will open the search location @IBAction func openStartLocation(_ sender: UIButton) { let autoCompleteController = GMSAutocompleteViewController() autoCompleteController.delegate = self // selected location locationSelected = .startLocation // Change text color UISearchBar.appearance().setTextColor(color: UIColor.black) self.locationManager.stopUpdatingLocation() self.present(autoCompleteController, animated: true, completion: nil) } // MARK: when destination location tap, this will open the search location @IBAction func openDestinationLocation(_ sender: UIButton) { let autoCompleteController = GMSAutocompleteViewController() autoCompleteController.delegate = self // selected location locationSelected = .destinationLocation // Change text color UISearchBar.appearance().setTextColor(color: UIColor.black) self.locationManager.stopUpdatingLocation() self.present(autoCompleteController, animated: true, completion: nil) } // MARK: SHOW DIRECTION WITH BUTTON @IBAction func showDirection(_ sender: UIButton) { // when button direction tapped, must call drawpath func self.drawPath(startLocation: locationStart, endLocation: locationEnd) } } // MARK: - GMS Auto Complete Delegate, for autocomplete search location extension ViewController: GMSAutocompleteViewControllerDelegate { func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) { print("Error (error)") } func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) { // Change map location let camera = GMSCameraPosition.camera(withLatitude: place.coordinate.latitude, longitude: place.coordinate.longitude, zoom: 16.0 ) // set coordinate to text if locationSelected == .startLocation { startLocation.text = "(place.coordinate.latitude), (place.coordinate.longitude)" locationStart = CLLocation(latitude: place.coordinate.latitude, longitude: place.coordinate.longitude) createMarker(titleMarker: "Location Start", iconMarker: #imageLiteral(resourceName: "mapspin"), latitude: place.coordinate.latitude, longitude: place.coordinate.longitude) } else { destinationLocation.text = "(place.coordinate.latitude), (place.coordinate.longitude)" locationEnd = CLLocation(latitude: place.coordinate.latitude, longitude: place.coordinate.longitude) createMarker(titleMarker: "Location End", iconMarker: #imageLiteral(resourceName: "mapspin"), latitude: place.coordinate.latitude, longitude: place.coordinate.longitude) } self.googleMaps.camera = camera self.dismiss(animated: true, completion: nil) } func wasCancelled(_ viewController: GMSAutocompleteViewController) { self.dismiss(animated: true, completion: nil) } func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = false } } public extension UISearchBar { public func setTextColor(color: UIColor) { let svs = subviews.flatMap { $0.subviews } guard let tf = (svs.filter { $0 is UITextField }).first as? UITextField else { return } tf.textColor = color }

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

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

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

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

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

guest

回答1

0

ベストアンサー

どこでエラーが出ているか、などの情報があるとより分かりやすいかと思うのですが、パッとみた感じViewController.googleMapsが初期化されずにnilになっているような気がします。

投稿2020/02/13 15:20

HidehisaArai

総合スコア64

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

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

BichaSoken

2020/02/13 15:36

ViewController.googleMap という箇所はないのですがどういう事でしょうか?
BichaSoken

2020/02/13 15:41

初学者なため、該当箇所などを詳しく教えていただくと助かります。
HidehisaArai

2020/02/13 15:51

ViewControllerの一番上で宣言されている ```swift var googleMaps: GMSMapView! ``` の部分ですが、これは`googleMaps`という変数がGMSMapViewという型をもつはずである、と宣言しているのみで実際の初期化は行われていません。なので、`viewDidLoad()`の中で`self.googleMaps`を参照する記述より前にGMSMapViewのインスタンスを作成して`googleMaps`に代入するなどしてあげないとエラーになります。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問