Jirakit Paitoonnaramit
Jirakit Paitoonnaramit

Reputation: 167

Swift google map not show

follow this code on Xcode9.2

@IBOutlet weak var mView: UIView!
let locationManager = CLLocationManager()
var mapView: GMSMapView!

var currentLatitude:Double = 0.0
var currentLongtitude:Double = 0.0
var heading = 0.00

override func viewDidLoad() {
    super.viewDidLoad()


    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

    let camera = GMSCameraPosition.camera(withLatitude: locationManager.location!.coordinate.latitude, longitude:
        locationManager.location!.coordinate.longitude, zoom: 15);

    mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera)
    mapView.delegate = self
    self.mView = mapView
    mapView.settings.myLocationButton = true
    mapView.isMyLocationEnabled = true
}

if I use

self.View = mapView

it work perfectly but

self.mView = mapView

it not work, why?? the mMapview is white.

Upvotes: 1

Views: 4207

Answers (2)

Alexander Gaidukov
Alexander Gaidukov

Reputation: 759

This line self.mView = mapView just change pointer mView from Outlet view to MapView, but it doesn't add the MapView as a subview. What you need to do is:

  1. Remove mView from Interface Builder. You don't need it at all.
  2. Replace self.mView = mapView with the following code: view.addSubview(mapView)
  3. Add all needed constraints. For instance:

    mapView.translatesAutoresizingMaskIntoConstraints = false
    
      NSLayoutConstraint.activate([
      mapView.topAnchor.constraint(equalTo: view.topAnchor),
      mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
      mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
      mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
    ])
    

Upvotes: 3

Jake T.
Jake T.

Reputation: 4378

If you've put a mapview on a storyboard or xib, you've overwritten it by assigning it with self.mView = mapView. Instead there should already be an instantiated self.mView, and you can change mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera) to self.mView.camera = camera, and all the other instances of mapView below to self.mView.

If you haven't, you can remove self.mView entirely and just work with mapView. Add in self.view.addSubview(mapView) to the bottom of your viewDidLoad and you'll be set.

Upvotes: 4

Related Questions