Google maps GMSMarker changes camera focus iOS - ios

I am having an issue that GMSMarker changes camera focus on any kind of popup alert or whenever I tap on marker and app navigates to google maps application. Following is my implementation. I add google maps container to my viewcontroller header in layoutsubviews method. No idea what's going on. Kindly help.
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
if mapView == nil
{
let camera = GMSCameraPosition.camera(withLatitude: 45.582045, longitude:74.32937, zoom: 14.0)
mapView = GMSMapView.map(withFrame: CGRect(x: 0, y: 0, width: self.mapContainerView.bounds.size.width, height: self.mapContainerView.bounds.size.height), camera: camera)
mapView.delegate = self
do {
// Set the map style by passing the URL of the local file.
if let styleURL = Bundle.main.url(forResource: "style", withExtension: "json") {
mapView.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
} else {
NSLog("Unable to find style.json")
}
} catch {
NSLog("One or more of the map styles failed to load. \(error)")
}
self.mapContainerView.addSubview(mapView)
mapView.settings.setAllGesturesEnabled(false)
let marker = AppointmentMapDataManager(mapView: mapView).setAppointmentMarker()
// let location = GMSCameraPosition.camera(withLatitude: marker.position.latitude,
// longitude: marker.position.longitude,
// zoom: 14)
// mapView.camera = location
var bounds = GMSCoordinateBounds()
bounds = bounds.includingCoordinate((marker as AnyObject).position)
let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsets(top: self.mapContainerView.frame.height/2 - 33, left: self.mapContainerView.frame.width/2 - 81, bottom: 0, right: 0))
mapView.moveCamera(update)
}
}

Instead of move your camera in the viewDidLayoutSubView which is a wrong approach use didTap method of the GMSMapViewDelegate or if you want to do it automatically use a execute after delay
//method for center camera based in your own code
func centerInMarker(marker: GMSMarker) {
var bounds = GMSCoordinateBounds()
bounds = bounds.includingCoordinate((marker as AnyObject).position)
let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsets(top: (self.mapView?.frame.height)!/2 - 33, left: (self.mapView?.frame.width)!/2 - 81, bottom: 0, right: 0))
mapView?.moveCamera(update)
}
You can use it in the delegate method
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
self.centerInMarker(marker: marker)
return true
}
Or simply when you add your marker, with delay
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.centerInMarker(marker: marker)
}

You should add in viewDidLoad method, and update frame in viewDidLayoutSubviews.

Related

How to zoom in and out with buttons on MGLMapView using Swift?

I'm a newbie and I am trying to make a simple map project. I want to zoom in and out with buttons on the map but it's not working. I already tried using MKMapView but I can't change MGLMapView to MKMapView.
I tried to set a mglMapCamera variable in MapView and use it in ContentView but it didn't work either.
Also in MapView on this line: mglMapView = mapView
I'm getting this warning:
Modifying state during view update, this will cause undefined behavior.
MapView
#State public var mglMapView = MGLMapView()
#State public var mglMapCamera = MGLMapCamera()
func makeUIView(context: Context) -> MGLMapView {
// read the key from property list
let mapTilerKey = getMapTilerkey()
validateKey(mapTilerKey)
// Build the style url
let styleURL = URL(string: "https://api.maptiler.com/maps/streets/style.json?key=\(mapTilerKey)")
// create the mapview
let mapView = MGLMapView(frame: .zero, styleURL: styleURL)
mglMapView = mapView
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.logoView.isHidden = true
mapView.setCenter(
CLLocationCoordinate2D(latitude: 47.127757, longitude: 8.579139),
zoomLevel: 10,
animated: true)
mapView.layoutMargins = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0)
// use the coordinator only if you need
// to respond to the map events
mapView.delegate = context.coordinator
return mapView
}
func updateUIView(_ uiView: MGLMapView, context: Context) {}
func makeCoordinator() -> MapView.Coordinator {
Coordinator(self)
}
final class Coordinator: NSObject, MGLMapViewDelegate {
var control: MapView
init(_ control: MapView) {
self.control = control
}
func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) {
// write your custom code which will be executed
// after map has been loaded
}
}
ContentView
var mapView = MapView()
#State var currentZoom:CGFloat = 10.0
func ZoominOutMap(level:CGFloat){
let camera = MGLMapCamera(lookingAtCenter: CLLocationCoordinate2D(latitude: 47.127757, longitude: 8.579139), fromEyeCoordinate: self.mapView.mglMapView.camera.centerCoordinate, eyeAltitude: 10)
self.mapView.mglMapView.setCamera(camera, animated: true)
}
Buttons in ContentView
VStack {
Button("+") {
currentZoom = currentZoom + 1
self.ZoominOutMap(level: currentZoom)
}
.frame(width: 30, height: 30)
.foregroundColor(Color.white)
.background(Color.gray)
.clipShape(Circle())
Button("-") {
currentZoom = currentZoom - 1
self.ZoominOutMap(level: currentZoom)
}
.frame(width: 30, height: 30)
.foregroundColor(Color.white)
.background(Color.gray)
.clipShape(Circle())
}
You can call a cameraUpdate for the same cameraPosition but zoom+=1 or -=1 to zoom in or out.
Then call animateCamera with that update and it should zoom in just fine.

iOS | Tapping on Marker Zooms out Google Map SDK

I have a GMSMapView instance, orderMapView, which is linked to my UIViewController. I give Location Permissions and later make self as delegate of orderMapView
orderMapView.delegate = self
I also make the class conform to GMSMapViewDelegate. I then initiate multiple markers in viewDidLoad, one of which is like this:
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: CLLocationDegrees(dataLat), longitude: CLLocationDegrees(dataLng))
marker.title = dataName
marker.snippet = "LAT: \(dataLat), LONG: \(dataLng)"
marker.appearAnimation = .pop
marker.map = orderMapView
marker.isDraggable = true
marker.isTappable = true
I also implement the following delegate methods:
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D){
//1 - IT NEITHER COMES HERE
print(coordinate)
}
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
print(position)
}
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
//2 - IT NEITHER COMES HERE
orderMapView.selectedMarker = marker
return true
}
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
let 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 = marker.title
view.addSubview(lbl1)
let lbl2 = UILabel(frame: CGRect.init(x: lbl1.frame.origin.x, y: lbl1.frame.origin.y + lbl1.frame.size.height + 3, width: view.frame.size.width - 16, height: 15))
lbl2.text = marker.snippet
lbl2.font = UIFont.systemFont(ofSize: 14, weight: .light)
view.addSubview(lbl2)
return view
}
I can see the markers on the map but when I tap it, the map zooms out and never shows the info windows on those markers. Please help.
UPDATE: This is happening on Simulator as I don't have a device. Can that be the sore and sole problem?

Cannot constantly update location on iOS xcode project

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.

Add a label on MGLPolygon

I have a situation where I need to draw an MGLPolygon on a map(MapBox) and I also want to give a UILabel like text on the polygon. The label has to be at the centroid of the polygon and it should be always visible. I found a code with which I can find the centroid of a given polygon, But I couldn't add a label to polygon. I have done the coding in SWIFT so swift developers please help me. Thanks in advance and Happy Coding :)
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
if let currentAnnotation = annotation as? AreaAnnotation {
let reuseIdentifier = currentAnnotation.areaTitle
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier!)
if annotationView == nil {
annotationView = MGLAnnotationView(reuseIdentifier: reuseIdentifier)
annotationView?.frame = CGRect(x: 0, y: 0, width: 120, height: 90)
annotationView!.backgroundColor = UIColor.clear
let detailsLabel:UILabel = UILabel()
detailsLabel.frame = CGRect(x: 30, y: 60, width: 60, height: 25)
detailsLabel.textAlignment = .center
detailsLabel.text = currentAnnotation.areaTitle
// detailsLabel.textColor = UIColor(red:175/255 ,green:255/255, blue:255/255 , alpha:0.75)
detailsLabel.textColor = UIColor.white
detailsLabel.font = UIFont(name: "HelveticaNeue-CondensedBlack", size: 15)
let strokeTextAttributes = [NSAttributedStringKey.strokeColor : UIColor.black, NSAttributedStringKey.strokeWidth : -5.0,] as [NSAttributedStringKey : Any]
detailsLabel.attributedText = NSAttributedString(string: titleLabel.text!, attributes: strokeTextAttributes)
detailsLabel.backgroundColor = UIColor.black.withAlphaComponent(1.0)
detailsLabel.clipsToBounds = true
detailsLabel.layer.cornerRadius = 5.0
detailsLabel.layer.borderWidth = 2.0
detailsLabel.layer.borderColor = UIColor.white.cgColor
annotationView?.addSubview(detailsLabel)
}
return annotationView
}
return nil
}
Thanks #jmkiley but I wanted to clear out that issue as fast as possible so I used this tweak, which was the exact thing I wanted.
If you have the center point of the polygon, you could use it to create a MGLPointFeature. Then create a MGLShapeSource and MGLSymbolStyleLayer with it. Provide the text to that layer. For example:
import Mapbox
class ViewController: UIViewController, MGLMapViewDelegate {
var mapView : MGLMapView!
var line: MGLPolyline?
override func viewDidLoad() {
super.viewDidLoad()
mapView = MGLMapView(frame: view.bounds)
view.addSubview(mapView)
mapView.delegate = self
let coords = [
CLLocationCoordinate2D(latitude: 38.0654, longitude: -88.8135),
CLLocationCoordinate2D(latitude: 41.7549, longitude: -88.8135),
CLLocationCoordinate2D(latitude: 41.7549, longitude: -83.1226),
CLLocationCoordinate2D(latitude: 38.0654, longitude: -83.1226)
]
let polygon = MGLPolygon(coordinates: coords, count: UInt(coords.count))
mapView.addAnnotation(polygon)
}
func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) {
let point = MGLPointFeature()
point.coordinate = CLLocationCoordinate2D(latitude: 40.0781, longitude: -85.6714)
let source = MGLShapeSource(identifier: "point-source", features: [point], options: nil)
style.addSource(source)
let layer = MGLSymbolStyleLayer(identifier: "point-layer", source: source)
layer.text = MGLStyleValue(rawValue: "Polygon A")
style.addLayer(layer)
}
}

Creating markers in GoogleMaps

How to create a function for drawing markers on a map from an array of applications received during the operation. That is, the function must be outside the viewDidLoad() ?
If you use a simple function with the following content:
import UIKit
import GoogleMaps
import CoreLocation
class ViewController: UIViewController {
#IBOutlet var mMap: GMSMapView!
let locationManager = CLLocationManager()
let mapInsets = UIEdgeInsets(top: 10.0, left: 0.0, bottom: 100.0, right: 0.0)
override func viewDidLoad() {
super.viewDidLoad()
view = mMap
mMap.padding = mapInsets
mMap.isMyLocationEnabled = true
mMap.settings.compassButton = true
mMap.settings.myLocationButton = true
mMap.settings.scrollGestures = true
mMap.settings.zoomGestures = true
let camera = GMSCameraPosition.camera(withLatitude: myLat, longitude: myLon, zoom: 15.0)
let mMap = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
let buttonDps = UIButton(frame: CGRect(x: 2, y: 520, width: 103, height: 45))
button.backgroundColor = .red
button.setTitle("yes", for: .normal)
button.titleLabel!.font = UIFont.boldSystemFont(ofSize: 19)
button.layer.cornerRadius = 5.0
button.addTarget(self, action: #selector(buttonAct), for:.touchUpInside)
self.view.addSubview(button)
}
func buttonAct(sender: UIButton!) {
let alert = UIAlertController(title:"help", message:"qwerty", preferredStyle:.alert)
alert.addAction(UIAlertAction(title:"OK", style:.default){ action in
self.markercreate()
})
alert.addAction(UIAlertAction(title:"cancel", style:.cancel, handler:nil))
self.present(alert, animated:true, completion:nil)
}
func markercreate(){
let marker2 = GMSMarker()
marker2.position = CLLocationCoordinate2D(latitude: 54.9044200, longitude: 52.3154000)
marker2.title = "Россия"
marker2.snippet = "Москва"
marker2.map = mMap
}
}
then nothing happens (((
Suppose you have a list of latitude, longitude and place name.
Create a loop and inside your loop if you want to show markers then use this.
func createMarker()
{
let lon = Double(longResult as! String)
let lat = Double(latResult as! String)
print("Center_Name: \(centerName)")
print("Longitude: \(longResult)")
print("Latitude: \(latResult)")
let markerResult = GMSMarker()
markerResult.position = CLLocationCoordinate2D(latitude: lat! , longitude: lon!)
markerResult.title = "\(centerName)"
markerResult.map = viewMap
}
The code I have shown is a basic one. With this you can create a marker on your map.
As far as I can analyze,
The code will work fine. Also the marker is added to the map. You just don't see the marker you have added. Move the camera position of the map to marker position so that you can see the marker, i.e.
func markercreate()
{
//Your code...
mMap.camera = GMSCameraPosition.camera(withLatitude: 54.9044200, longitude: 52.3154000, zoom: 15.0) //Add this line to your code
}
I assume you will resolve the 2 mMap variables that you have created as I mentioned in the comment.
Edit:
1. In Storyboard, set the ViewController's view's class to GMSMapView and connect the outlet mMap to it, i.e.
2. Follow the comments in the below code snippet:
override func viewDidLoad()
{
super.viewDidLoad()
//Your code...
view = mMap //Remove this line
mMap.camera = GMSCameraPosition.camera(withLatitude: 54.9044200, longitude: 52.3154000, zoom: 15.0) //Add this line
let camera = GMSCameraPosition.camera(withLatitude: myLat, longitude: myLon, zoom: 15.0) //Remove this line
let mMap = GMSMapView.map(withFrame: CGRect.zero, camera: camera) //Remove this line
//Your code...
}

Resources