I am trying to set a GoogleMap to a UIView and add it as a Subview. However, when running the app I get this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
It crashes at code line:
mapView.camera = camera
Here's my full ViewController code:
class LocationViewController: UIViewController {
#IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
let camera = GMSCameraPosition.camera(withLatitude: 15.4989, longitude: 73.8278, zoom: 6)
mapView.camera = camera
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
self.view.addSubview(self.mapView)
}
}
I went through a few other similar SO threads and all of them have the same code. In my case the UI freezes and crashes with this error. What am I doing wrong?
EDIT
Yes, I have set the UIView's custom class as GMSMapView
Could you please use below code and try:
override func viewDidLoad() {
super.viewDidLoad()
let camera = GMSCameraPosition.camera(withLatitude: 15.4989, longitude: 73.8278, zoom: 6)
mapView.camera = camera
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
self.view.addSubview(self.mapView)
}
you have to do it like this
you have to give frame to GMSMapview
Here in this line self.view.bounds , you have to set your custom view
let camera = GMSCameraPosition.camera(withLatitude: 15.4989,
longitude: 73.8278,
zoom: 6)
let mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera)
This is the syntax in swift 3.0
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
print(locations)
mapview.delegate = self
currentLocation = CLLocationCoordinate2D(latitude:CLLocationDegrees(locations[0].coordinate.latitude), longitude:CLLocationDegrees(locations[0].coordinate.longitude))
mapview.camera = GMSCameraPosition.camera(withTarget:locations[0].coordinate, zoom: 10.0)
mapview.isMyLocationEnabled = true
}
Related
I have followed GoogleMaps SDK. The map shows well. MyLocation, zoom-in, zoom-out all work well.
The issue is when I click "myLocation" button after zoom-in or zoom-out and move to other location, the map will go back to my location, BUT the zoom stays as zoom-in or zoom-out level. It doesn't get back to original zoom level. My code is as follow:
//googleMap
var locationManager = CLLocationManager()
var currentLocation: CLLocation?
var mapView: GMSMapView!
var placesClient: GMSPlacesClient!
var zoomLevel: Float = 15.0
// An array to hold the list of likely places.
var likelyPlaces: [GMSPlace] = []
// The currently selected place.
var selectedPlace: GMSPlace?
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.distanceFilter = 50
locationManager.startUpdatingLocation()
locationManager.delegate = self
let camera = GMSCameraPosition.camera(withLatitude: 43.6532,
longitude: 79.3832,
zoom: zoomLevel)
mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
mapView.settings.myLocationButton = true
mapView.settings.compassButton = true
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.isMyLocationEnabled = true
// Add the map to the view, hide it until we've got a location update.
view.addSubview(mapView)
mapView.isHidden = true
placesClient = GMSPlacesClient.shared()
}
In my CLLocationManagerDelegate I have:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
print("Location: \(location)")
let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude,
longitude: location.coordinate.longitude,
zoom: zoomLevel)
mapView.camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude,
longitude: location.coordinate.longitude,
zoom: zoomLevel)
if mapView.isHidden {
mapView.isHidden = false
mapView.camera = camera
} else {
mapView.animate(to: camera)
}
}
I am trying to create a mock up app that shows the campus of my school. I want to be able to search through the campus and then click the location button to have the screen follow my location. Check video below to understand my issue. My code is proprietary as i am brand new to swift and xcode. I am not using the story board, just programatically creating this app. When i do get the location to consistently update my location and follow my simulation location, it tears down the view and rebuilds it, which leads to it looking very glitchy. Also, i cannot break the update by changing moving the camera somewhere else. Im sure im missing something quite big. To make as much sense as possible, i want to be able to follow the location on screen in a smooth look, as well as stop the updating location so that can search the campus without my screen updating to my current location.
video link: [https://www.dropbox.com/s/op2kw9sfk0c8dm5/Xcode%20problem.mp4?dl=0][1]
here is my code:
import UIKit
import GoogleMaps
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate{
lazy var mapView = GMSMapView()
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
GMSServices.provideAPIKey("AIzaSyBXEZf5gq-ewIjmlzyWlsDHJSsOTsHCm4k")
let camera = GMSCameraPosition.camera(withLatitude: 35.046462, longitude: -85.298153, zoom: 15.8, bearing: 295, viewingAngle: 0)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.mapType = .satellite
//view = mapView
//User Location
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
locationManager.stopUpdatingLocation()
view = mapView
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: 15.8, bearing: 295, viewingAngle: 0)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.mapType = .satellite
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
showMarker(position: CLLocationCoordinate2D.init(latitude: 35.046462, longitude: -85.298153), markerTitle: "Cardiac Hill", markerSnippet: "UTC")
showMarker(position: CLLocationCoordinate2D.init(latitude: 35.047488, longitude: -85.300121), markerTitle: "Library", markerSnippet: "UTC")
view = mapView
}
func showMarker(position: CLLocationCoordinate2D, markerTitle: String, markerSnippet: String){
let marker = GMSMarker()
marker.position = position
marker.title = "\(markerTitle)"
marker.snippet = "\(markerSnippet)"
marker.tracksViewChanges = true
marker.opacity = 0.75
marker.icon = GMSMarker.markerImage(with: .white)
marker.map = mapView
}
func markerInfo(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
var view = UIView(frame: CGRect.init(x: 0, y: 0, width: 200, height: 70))
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 6
let lbl1 = UILabel(frame: CGRect.init(x: 8, y: 8, width: view.frame.size.width - 16, height: 15))
lbl1.text = "Cardiac label"
view.addSubview(lbl1)
let lbl2 = UILabel(frame: CGRect.init(x: lbl1.frame.origin.x, y: lbl1.frame.origin.y + lbl1.frame.origin.y + 3, width: view.frame.size.width - 16, height: 15))
lbl1.text = "lbl2 info"
view.addSubview(lbl2)
return view
}
}
Thank you for your time, I will be sure to check this almost everyday to respond to any addition information needed. PS, i already did api and sdk importing, as well as added info into info.plist. I seem to get everything to work but this issue.
import UIKit
import GoogleMaps
import FirebaseDatabase
import GeoFire
class MapViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
var mapView = GMSMapView()
var locationManager: CLLocationManager!
let regionRadius: CLLocationDistance = 1000
var place = CLLocationCoordinate2D()
#IBOutlet var myLocationButton: UIButton!
#IBOutlet var infoWindow: UIView!
#IBOutlet var postTitle: UILabel!
#IBOutlet var postImage: UIImageView!
var showing = false;
var pins = [String: Pin]()
var currentMarker = GMSMarker()
override func viewDidLoad() {
super.viewDidLoad()
// sets up the map view (camera, location tracker etc.)
let camera = GMSCameraPosition.camera(withLatitude: place.latitude, longitude: place.longitude, zoom: 17.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.isMyLocationEnabled = true
mapView.delegate = self
view = mapView
self.view.addSubview(myLocationButton)
self.view.bringSubview(toFront: myLocationButton)
// Location manager
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.startUpdatingLocation()
// Get nearby records
let geoFire = GeoFire(firebaseRef: FIRDatabase.database().reference().child("geofire"))
let query = geoFire?.query(at: CLLocation(latitude: place.latitude, longitude: place.longitude), withRadius: 0.6)
_ = query?.observe(.keyEntered, with: { (key, location) in
let marker = GMSMarker()
let newPin = Pin(title: "post", locationName: "\(key!)", discipline: "", coordinate: (location?.coordinate)!)
self.pins[newPin.locationName] = newPin
marker.icon = UIImage(named: "icon_small_shadow")
marker.position = Pin.coordinate
marker.title = Pin.title
marker.snippet = Pin.locationName
marker.map = mapView
})
myLocationTapped(myLocationButton)
}
// sets the info in the custom info window
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
if(currentMarker == marker && showing) {
infoWindow.isHidden = true
showing = false
} else {
infoWindow.isHidden = false
self.view.addSubview(infoWindow)
self.view.bringSubview(toFront: infoWindow)
postTitle.text = marker.snippet
showing = true
}
currentMarker = marker
return true
}
#IBAction func myLocationTapped(_ sender: Any) {
print("tapped")
let cameraPosition = GMSCameraPosition.camera(withLatitude: place.latitude, longitude: place.longitude, zoom: 15.0)
mapView.animate(to: cameraPosition)
}
I have the following code set up, designed to place a button on the google maps map that when tapped, animates the google maps camera to that location. However, my code doesn't work. The "tapped" prints in the console but the camera doesn't budge. I haven't been able to find an answer anywhere for this, so any help would be appreciated.
EDIT: Added full code for the Map View Controller
In my case the map wasn't updating because I was not calling the method on the main queue. The following code solved the issue:
DispatchQueue.main.async {
self.mapView.animate(to: camera)
}
Anything action related to the user interface should be called in the main queue
Try this way
let cameraPosition = GMSCameraPosition.camera(withLatitude: place.latitude, longitude: place.longitude, zoom: 15.0)
mapView.animate(to: cameraPosition)
Edit: Issue is you aren't having the reference of your map with your mapView object, change your viewDidLoad's line:
view = mapView
TO:
// sets up the map view (camera, location tracker etc.)
let camera = GMSCameraPosition.camera(withLatitude: place.latitude, longitude: place.longitude, zoom: 17.0)
let mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
mapView.isMyLocationEnabled = true
mapView.delegate = self
self.mapView = mapView
view.addSubview(self.mapView)
This is the current code, after making the edits suggested, it no longer shows a marker on the map for Sydney Australia
class LocateVC: UIViewController {
#IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
//override func loadView() {
// Create a GMSCameraPosition that tells the map to display the
// coordinate -33.86,151.20 at zoom level 6.
let camera = GMSCameraPosition.camera(withLatitude: -33.86 , longitude: 151.20, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: self.mapView.bounds, camera: camera)
self.mapView = mapView
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
}
}
Output
This is the screen that loads
And no marker on Sydney Australia
Your are setting mapview to main view of ViewController
So Change your these two lines
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = mapView
With:
let mapView = GMSMapView.map(withFrame: self.mapView.bounds, camera: camera)
self.mapView = mapView
The answer from #Nirav is almost there
here what I did:
import UIKit
import GoogleMaps
class AddressMapController: UIViewController {
#IBOutlet weak var map123: GMSMapView! // this is linked to a UIView in storyboard
var currentLocation: CLLocation! //this is passed from the main controller
override func viewDidLoad() {
super.viewDidLoad()
let lat = currentLocation.coordinate.latitude
let long = currentLocation.coordinate.longitude
let camera = GMSCameraPosition.camera(withLatitude: lat , longitude: long, zoom: 12)
// Creates a marker in the center of the map.
let currentLocation_Marker = GMSMarker()
currentLocation_Marker.position = CLLocationCoordinate2D(latitude: lat, longitude: long)
currentLocation_Marker.title = "My Current Location"
currentLocation_Marker.snippet = "I am here now"
currentLocation_Marker.map = map123
self.map123.camera = camera
}
}
hope it will help somebody in the future
Hello i was trying to put map in subview but when i put google map in sub view it doesn't work marker and GPS Coordinates don't work
-With Sub View
-Without Sub View
-SWIFT CODE
import UIKit
import GoogleMaps
class HomeViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var mapView: GMSMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
let camera = GMSCameraPosition.cameraWithLatitude(15.4989, longitude: 73.8278, zoom: 6)
let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
mapView.myLocationEnabled = true
// self.view = mapView
self.view.addSubview(mapView)
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(15.4989, 73.8278)
marker.title = "Panjim"
marker.snippet = "Near Don Bosco,Alphran Plaza"
marker.map?.addSubview(mapView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thanks in advance
I found the solution. The problem was : i was creating a new map, then was adding a marker to that new map. Then with the new map i was doing nothing.
So here is my Solution :
#IBOutlet weak var subviewMap: GMSMapView!
func loadMap() {
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 10.0)
subviewMap.camera = camera
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = subviewMap
}
And it works.
NOTE : Do not forget to Mention your subview as GMSMapView class in IB
Thanks #O-mkar and #mixth for efforts.
Happy Coding :]
Here is the solution to add marker
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(lat, long)
marker.appearAnimation = kGMSMarkerAnimationPop
marker.title = "Marker" // Marker title here
marker.snippet = "Tap the ↱ Navigate button to start navigating."
marker.infoWindowAnchor = CGPoint(x: 0.5, y: 0)
marker.icon = UIImage(named: "marker") //Set marker icon here
marker.map = self.mapView // Mapview here
Animate Camera to position
let camera = GMSCameraPosition.camera(withLatitude: 15.4989, longitude: 73.8278, zoom: 17)
mapView.animate(to: camera)
I have my GMSMapView inside another UIView and everything just works fine. The only different line is:
marker.map = mapView
after adding marker you should add some delay with this approach i have added 2 marker with bounds
DispatchQueue.main.async {
if self.markerArray.count > 1 {
var bounds = GMSCoordinateBounds()
for marker in self.markerArray {
marker.map = self.mapView
bounds = bounds.includingCoordinate(marker.position)
}
self.isMovedTheMap = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.9, execute: {
self.superTopView.fadeOut()
let update = GMSCameraUpdate.fit(bounds, withPadding: 80)
self.mapView.animate(with: update)
})
}
}