Google Map flickering in iOS - ios

I am using Google Maps SDK for iOS version: 1.10.17867.0 in my app via pod. But when I initialise the map at a particular position, all the titles and map starts flickering.
Example Code (swift):
import UIKit
import GoogleMaps
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor();
var camera = GMSCameraPosition.cameraWithLatitude(19.0176147, longitude: 72.8561644, zoom:18)
// even try this: 28.6469655, longitude: 77.0932634, zoom:10
var mapView = GMSMapView.mapWithFrame(CGRectZero, camera:camera)
var marker = GMSMarker()
marker.position = camera.target
marker.snippet = "Hello World"
marker.appearAnimation = kGMSMarkerAnimationPop
marker.map = mapView
self.view = mapView
}
}

I have figured out the reason.
If you are using an incorrect google maps api key, or correct key with insufficient permissions, then this will happen. It was the latter reason for us.
For further reading, documentation link, although the said behaviour is not mentioned anywhere. It should rather log an error message.

Related

Plotting a Specific Location on map view with latitude and longitude

I want to plot a specific point on the map having the lat and lon from an api.
Program flow:
Get LAT & LON from api (done)
Ping api again via timer after every 5 seconds to get the latest location (done)
Plot location with retrieved LAT & LON on map
The issue is every code on the net has to do with 2 points, so user loc and destination loc. I cant seem to get it to work without user loc. I have however coded this to plot the location. However, with this when I touch the map, the map zooms out. Another issue is when I get another point the previous one also remains on the screen. (for testing purpose I hard coded the lat and lon but when I connect the api code that refreshes, prior points remain and the map code is the same as this. The lat and lon are passed via func parameters in createAnnotation().)
My code:
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self // or connect in storyboard
createAnnotation()
}
func createAnnotation(){
let annotations = MKPointAnnotation()
annotations.coordinate = CLLocationCoordinate2D(latitude: 41.87369, longitude: -87.813293)
mapView.addAnnotation(annotations)
}}
How Do I plot the coordinates properly? and then delete the prior and show the new one?.
For the "previous one also remains on the screen" problem: don't keep making a new annotation and calling addAnnotation if you don't want to keep adding new annotations. Instead, keep hold of the annotation that you add, and move it later using its coordinate property. Something like this maybe:
class ViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
var annotationForThing: MKPointAnnotation?
var coordinateOfThing: CLLocationCoordinate2D? {
didSet {
guard let newCoord = coordinateOfThing else {
if let existing = annotationForThing {
mapView.removeAnnotation(existing)
}
return
}
if let existing = annotationForThing {
existing.coordinate = coordinateOfThing
}
else {
let newAnnotation = MKPointAnnotation()
newAnnotation = coordinateOfThing
mapView.addAnnotation(newAnnotation)
annotationForThing = newAnnotation
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self // or connect in storyboard
}

Google Maps GMSPanoramaView api blocked

I'm getting this error:
This application has been blocked by the Google Maps API. This might be because of an incorrectly registered key.
When I try to set google maps panorama street view. If I display a regular map view, it works so seems like the key is registered properly.
I followed the directions for a panorama view exactly as per google docs:
import UIKit
import GoogleMaps
class ViewController: UIViewController, GMSMapViewDelegate {
override func loadView() {
let panoView = GMSPanoramaView(frame: .zero)
self.view = panoView
panoView.moveNearCoordinate(CLLocationCoordinate2D(latitude: -33.732, longitude: 150.312))
}
}
Any ideas?
For me, the solution was that I needed to link my project in Google Cloud Platform to a billing account.
Once I did that the street view started working correctly.
The standard Google map worked fine without a billing account, which confused me initially.
You need to configure the delegate for this object. Something like:
import UIKit
import GoogleMaps
class ViewController: UIViewController, GMSMapViewDelegate {
override func loadView() {
let panoView = GMSPanoramaView(frame: .zero)
panoView.delegate = self
self.view = panoView
panoView.moveNearCoordinate(CLLocationCoordinate2D(latitude: -33.732, longitude: 150.312))
}
}
extension ViewController: GMSPanoramaViewDelegate {
func panoramaView(_ view: GMSPanoramaView, error: Error, onMoveNearCoordinate coordinate: CLLocationCoordinate2D) {
print("error: \(error.localizedDescription)")
}
}

can't show map annotation in Swift

I am trying to add map annotation, but when i try to run the app, the map annotation doesnt show, and give error message.
Add Map Annotation[3668:68848] Could not inset legal attribution from
corner 4
actually I just follow along a tutorial on Youtube in here https://www.youtube.com/watch?v=hRextIKJCnI , in swift3 this code seems work, but I don't know why it doesnt work in me. I am using swift 4 and Xcode 9.2
I have tried a solution from stack overflow but it doesn't work in me, in here Could not inset legal attribution from corner 4 swift
What went wrong in here?
import UIKit
import MapKit
class ViewController: UIViewController {
#IBOutlet weak var mapKitView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let span : MKCoordinateSpan = MKCoordinateSpanMake(0.001, 0.001)
let location : CLLocationCoordinate2D = CLLocationCoordinate2DMake(-6.239116, 106.789415)
let region : MKCoordinateRegion = MKCoordinateRegionMake(location, span)
mapKitView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.title = "My Shop"
annotation.subtitle = "Come visit here"
mapKitView.addAnnotation(annotation)
}
}
You are saying:
let annotation = MKPointAnnotation()
annotation.title = "My Shop"
annotation.subtitle = "Come visit here"
mapKitView.addAnnotation(annotation)
And that's all you're saying. But... That annotation has no coordinate! So how do you imagine the map can possibly know where it's supposed to go?

Current location in not working in Google Map

I have integrated google map in swift 3, when map screen appear than current location in not showing, i have added two keys in .plist file and also set CLLocationManager delegate and requestAlwaysAuthorization
class MapViewController: UIViewController, CLLocationManagerDelegate, UITextFieldDelegate {
#IBOutlet var mapView: GMSMapView!
var marker: GMSMarker?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "MapVC"
self.doSetupUI()
self.searchLocation()
}
override func viewWillAppear(_ animated: Bool) {
let locationManager : CLLocationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
}
func doGoogleMapSetup(lat : Double , lng : Double) {
let camera = GMSCameraPosition.camera(withLatitude: lat, longitude:lng, zoom:16)
let mapView = GMSMapView.map(withFrame: .zero, camera:camera)
mapView.isMyLocationEnabled = true
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lng)
marker.snippet = ""
marker.appearAnimation = kGMSMarkerAnimationPop
marker.map = mapView
let arrPoints : NSMutableArray = NSMutableArray()
arrPoints.add(UserDefaults.standard.object(forKey: "addressPoints"))
for i in 0..<arrPoints.count {
let path : String = (arrPoints.object(at: i)as! NSMutableArray).object(at: 0) as! String
let route : GMSPath = GMSPath.init(fromEncodedPath: path)!
let polyLine : GMSPolyline = GMSPolyline.init(path: route)
polyLine.strokeWidth = 2.0
polyLine.strokeColor = UIColor.red
polyLine.map = mapView
}
}
For showing current location we don't need any location manager in case of GoogleMaps. All we need is to add one of the keys or both in the .plist. So make sure the key is there. I have used NSLocationWhenInUseUsageDescription key.
<key>NSLocationWhenInUseUsageDescription</key>
<string>Allow location</string>
Also make sure that you have called GMSServices provideAPIKey method and replaced with the API_KEY you generated in google developer console. Also all the relevant Google APIs as per requirement should be enabled.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
GMSServices.provideAPIKey("YOUR_API_KEY")
return true
}
So, I am assuming you have done all the settings and things right in google developer console.
By just writing the below line in your controller where you have made the GoogleMap can show the location allow/disallow prompt and take the permission of the user.
mapView.isMyLocationEnabled = true
However this will not animate your map to your current location. But you can manually drag the map to check the current location and you will see a blue dot at your current location.
But now we also want to animate to the current location whenever we load that ViewController. Now the need for CLLocationManager arrives. So that in its didUpdateLocation delegate, we can fetch the current location and can just animate the graph to the current location.
So here is my complete controller.
import UIKit
import GoogleMaps
class ViewController: UIViewController,GMSMapViewDelegate,CLLocationManagerDelegate {
#IBOutlet weak var mapView: GMSMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
mapView.isMyLocationEnabled = true
mapView.delegate = self
//Location Manager code to fetch current location
self.locationManager.delegate = self
self.locationManager.startUpdatingLocation()
}
//Location Manager delegates
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude:(location?.coordinate.longitude)!, zoom:14)
mapView.animate(to: camera)
//Finally stop updating location otherwise it will come again and again in this delegate
self.locationManager.stopUpdatingLocation()
}
}
Another way of doing is not using the didUpdateLocation and not using the location manager is just by using the GMSMapViewDelegate delegate method mapViewDidFinishTileRendering
func mapViewDidFinishTileRendering(_ mapView: GMSMapView) {
let location = mapView.myLocation
let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude:(location?.coordinate.longitude)!, zoom:14)
mapView.animate(to: camera)
}
It will be called everytime the map rendering is finished.
But this comes with a limitation, it will always bring you to the current location whenever you drag/pinch/zoom map as the rendering finish everytime you play with map. So, you can just implement some kind of bool variable logic here.
You can get your location by using
let yourCurrentLocation = mapView.myLocation
Make sure to do this on a device rather than simulator. If you are using simulator, you have to choose some custom location and then only you will be able to see the blue dot.
I already gave this type of answer. Check this Link. But that was in Swift 2.x. The one which I posted in this answer is in Swift 3.x
This is a bit detailed, so I'd like to leave it in a full answer. This is the most common reason I have encountered for a nil location, since figuring out the basics, a few years ago. So, you call CLLocationManager.startLocating(), in your viewDidLoad. Then you call the method that sets up your map. Sometimes this works, and sometimes it doesn't, because of a race condition caused by the amount of time it takes the CLLocationManager to set up permissions, on the one hand, and access the user's location, in another part of the code. Let's look at an order of events, where it doesn't work:
1) you call requestAlwaysAuthroization and startLocating
2) User permissions setup is triggered on one thread
3) In your ViewController, you request the user's location, to set up your map
4) It comes back nil
5) NOW, step 2 finishes, and the app has access to the user's location, but it's too late
The core problem, is that the process that starts with requesting permissions and location, takes more than a few milliseconds. And if your view is already set up, it takes few milliseconds for it to go through the methods in your viewDidLoad. By the time you have the location you need, you've already requested it. This has caused me too many crashes, in my location-based apps.
My workaround, has been to craft a singleton CLLocationManager, make my starting view a delegate, and requestAlwaysAuthorization and startLocating, in that view. That way, when I get to the view that needs the location, the app has already started locating, and the locationManager.location is not nil.
This is an approach that will obviously not work for every app. If you need clarification, let me know, and if you need code, as well. I have a few public iO git repos, with projects where I have encountered and fixed this problem.

Swift/GMaps - keep getting an error

Please note - I have checked through SO for an answer to this. Many developers have answered, however I feel I have done what was needed.
I added the -ObjC to the project: Other Linker Flags.
I keep getting this error:
NSInvalidArgumentException', reason: '-[GMSMapView
animateToCameraPosition:]: unrecognized selector sent to instance
I have followed Googles steps - step by step as well as watching a number of videos (which are in ObjC) and reading a number of blogs.
I have added all frameworks and even unticked do not copy when adding the GMaps bundle.
Here is my code.
AppDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.enableLocalDatastore()
Parse.setApplicationId("ParseKey_eOHadu2GEOBqxvRl8ijKM0PMhq3", clientKey: "ParseKey_yFjq2MWocV3188hOq9MIjhqi5x0Od")
PFFacebookUtils.initializeFacebook()
GMSServices.provideAPIKey("MyKey_Pq9rjt5ZFX_jpB_QF5pEarMdp18_x4")
return true
}
Here is my viewController code
class UserLocationGm: UIViewController , GMSMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
var camera = GMSCameraPosition.cameraWithLatitude(-33.86,
longitude: 151.20, zoom: 6)
var mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
mapView.myLocationEnabled = true
self.view = mapView
var marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(-33.86, 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
}
Is something missing? i.e. I'm fairly sure that I am not meant to add a MapKit View to the viewController. Has anyone got any suggestions?
Xcode 6
Google Maps SDK: 1.9.1
Lang: Swift

Resources