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...
}
Related
I am new in iOS development.
I am drawing a circle on user location and I want to add the title to the circle.
I am using following code
var cirlce: GMSCircle!
let myPlacelatitude = (locationManager.location?.coordinate.latitude)! let myPlacelongitude = (locationManager.location?.coordinate.longitude)!
let userLocation = GMSCameraPosition.camera(withLatitude: myPlacelatitude,
longitude: myPlacelongitude,
zoom: 7.5)
mapView.camera = userLocation
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(myPlacelatitude, myPlacelongitude)
marker.title = ""
marker.snippet = ""
marker.map = mapView
let camera = GMSCameraPosition.camera(withLatitude: myPlacelatitude,
longitude: myPlacelongitude, zoom: 6)
cirlce = GMSCircle(position: camera.target, radius: 50000)
cirlce.fillColor = UIColor.green.withAlphaComponent(0.5)
cirlce1.isTappable = true
// the title is not setting to the circle in google map
cirlce.title = "40 KM"
cirlce.map = mapView
The documentation regarding GMSCircle states that some overlays, such as markers, will display the title on the map. I am not sure if this also holds true when using GMSCircle.
However as a workaround for your issue, you can put label in the GMSCircle when using GMSMarker with UIlabel from the SO answer in the comment of Mamaessen above. Here is the code snippet incorporated in GMSCircle:
class ViewController: UIViewController {
override func loadView() {
var circle: GMSCircle!
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 9.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = mapView
circle = GMSCircle(position:camera.target , radius: 50000)
circle.fillColor = UIColor.green.withAlphaComponent(0.5)
circle.strokeColor = .blue
circle.strokeWidth = 2
circle.title = "THIS IS CIRCLE"
circle.map = mapView
let labelMarker = GMSMarker(position: camera.target)
let label = UILabel()
label.text = circle.title
label.textColor = UIColor.red
label.sizeToFit()
labelMarker.iconView = label
labelMarker.map = mapView
}
}
If you want it to show after you tap the circle just like a popup when the circle is clicked, you can use an image which is a circle and use this as an icon to your marker and your text label should be in the marker title. The following is how I implement it in the code. Just a note you can notice the line marker.icon = UIImage(named: "circle"), this is where you put the name of the image that you want as your marker. In my case I made a New Image Set in my Assets and put the image I want to use as my custom marker.
lass ViewController: UIViewController {
override func loadView() {
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 9.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = 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.icon = UIImage(named: "circle")
marker.map = mapView
}
}
Hope this helps!
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.
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)
}
}
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)
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)
})
}
}