Supratik Majumdar Supratik Majumdar - 3 months ago 17
Swift Question

Google Maps shows different location, compared to input

Google Maps works perfectly fine when it is allowed to display on the main view.

But, as I use a new Sub the location of the maps is wrong and does not seem to change even with the change in the latitude and longitude values.

Code Snippet:

import UIKit
import GoogleMaps

class MainVC: UIViewController {


@IBOutlet weak var mapSubView: GMSMapView!

override func viewDidLoad() {

let camera = GMSCameraPosition.cameraWithLatitude(13.009047, longitude: 77.652949, zoom: 6)
let mapView = GMSMapView.mapWithFrame(self.mapSubView.bounds, camera: camera)

mapView.myLocationEnabled = true

self.mapSubView = mapView


// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: 13.009047, longitude: 77.652949)
marker.title = "Bangalore"
marker.snippet = "India"
marker.map = mapView
}

}


App Screenshot:
enter image description here

Answer

Add this line to your code:-

 mapSubView.camera = GMSCameraPosition(target: CLLocationCoordinate2D(latitude: 13.009047, longitude: 77.652949), zoom: 15, bearing: 0, viewingAngle: 0)

GoogleMaps camera just defines the orientation of the map along with the properties such as how much zoom do you want, whats the target of Zoom etc..For more details about this function and what the parameters represent CMD+CLICK on this function to go to its documentaion

EDIT: The above code was adding a new GMSMapView, using code in the View Controller above the already existing GMSMapView that was configured using the IBOutlet

Updated Code:

@IBOutlet weak var mapSubView: GMSMapView!

override func viewDidLoad() {


    mapSubView.myLocationEnabled = true
    mapSubView.camera = GMSCameraPosition(target: CLLocationCoordinate2D(latitude: 13.009047, longitude: 77.652949), zoom: 15, bearing: 0, viewingAngle: 0)


    // Creates a marker in the center of the map.
    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: 13.009047, longitude: 77.652949)
    marker.title = "Bangalore"
    marker.snippet = "India"
    marker.map = mapSubView
}

Google Maps iOS SDK Docs: GMSCameraPosition Class Reference

Google Maps iOS SDK Docs: GMSMarker Class Reference