Adding userlocation annotation by tap - ios

How can I add an annotation to mapView when a button is tapped? The annotation is placed from the user location.
My code below will run successfully, but when you tap the button addAnnotation, the app will crash. It says:
fatal error: unexpectedly found nil while unwrapping an Optional value
var myLocation : CLLocation!
#IBAction func addAnnotation(sender: UIBarButtonItem) {
let center = CLLocationCoordinate2D(latitude: myLocation.coordinate.latitude, longitude: myLocation.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.myLocation = locations.last as CLLocation!
}
let addPin = MKPointAnnotation()
addPin.coordinate = center
addPin.title = "ENDELIG!"
self.mapView.addAnnotation(addPin)
}
}

Related

How to make an app display a map with the users current location and then direct said user to a set location?

The code I'm using at the moment is:
import UIKit
import MapKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
openMapForPlace()
}
func openMapForPlace() {
let coordinate = CLLocationCoordinate2DMake(-37.688607,144.890787)
let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary:nil))
mapItem.name = "Gladstone Park Secondary College"
mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving])
}
The only thing it shows is a map of Australia and outputs this - Could not inset legal attribution from corner 4.
try this code, my be work for you.
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if userLocation != nil {
locationManager.stopUpdatingLocation()
mapView.camera = GMSCameraPosition(target: selectedCoordinate!.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
} else if let location = locations.first {
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
locationManager.stopUpdatingLocation()
}
}
try this
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let location = locations.last as CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}

Mapkit - Swift4 - How to disable Auto zooming

Apologies for the absurdely junior question but for some reason I can't grasp how to stop this from happening.
When I run the app, and I pinch to zoom into the map (or out, or navigate away from my position) the app will always pull me back to a set height and to my location. I'd like to not have this happen and just have the experience of zooming to whatever level and moving around without being interrupted.
Any ideas?
Here's the code snip from my VC:
let regionRadius: CLLocationDistance = 2000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius, regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let center = location.coordinate
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let region = MKCoordinateRegion(center: center, span: span)
mapView.setRegion(region, animated: true)
mapView.showsUserLocation = true
}
Thanks for any help
Location Manager delegate methods can be called very frequently and at any time. So you need to stop updating locations.
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
manager.stopUpdatingLocation()
manager.delegate = nil
let location = locations[0]
...
}

I wanted to add a annotation point in my project using swift. But I does not add on my simulator

I am adding the annotation whenever the location gets updated but it does not work for simulator.
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
print("my Current location is \(location?.coordinate.latitude) ")
let center = CLLocationCoordinate2D(latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
let myCurrentLocation = MKPointAnnotation()
myCurrentLocation.coordinate=center
myCurrentLocation.title = "Where I am"
myCurrentLocation.subtitle = "Here I am"
self.mapView .addAnnotation(myCurrentLocation)
}

Saving map pins to array, Swift

I am creating a map type application, once the user presses a button a pin is dropped to the map at their current location. I am trying to save map pins to an array so that they remain once the app is closed.
Here is my code so far:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.004, longitudeDelta: 0.004))
self.placesMap?.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Error code: " + error.localizedDescription)
}
// Add button action
#IBAction func addButton(sender: AnyObject) {
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: self.placesMap.userLocation.coordinate.latitude, longitude: self.placesMap.userLocation.coordinate.longitude)
self.placesMap.addAnnotation(annotation)
self.locationManager.startUpdatingLocation()
}
How can I save the pin information to an array which is reloaded each time the app is opened?
If you want to persist data between application launches, and you are not storing much data, the easy way is to use NSUserDefaults. You can do this by saying something like:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.004, longitudeDelta: 0.004))
self.placesMap?.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
let locationDictionary:[String:Double] = ["latitude":center.latitude,"longitude":center.longitude]
var locationArray = [[String:Double]]()
if NSUserDefaults.standardUserDefaults().objectForKey("locationArray") != nil {
locationArray = NSUserDefaults.standardUserDefaults().objectForKey("locationArray") as! [[String:Double]]
}
locationArray.append(locationDictionary)
NSUserDefaults.standardUserDefaults().setObject(locationArray, forKey: "locationArray")
NSUserDefaults.standardUserDefaults().synchronize()
}
You will then need to read out those locations when the app relaunches. You can do that in viewDidLoad. For example:
override func viewDidLoad(){
super.viewDidLoad()
if NSUserDefaults.standardUserDefaults().objectForKey("locationArray") != nil {
for dictionary in NSUserDefaults.standardUserDefaults().objectForKey("locationArray") as! [[String:Double]]{
let center = CLLocationCoordinate2D(latitude: dictionary["latitude"]!, longitude: dictionary["longitude"]!)
let annotation = MKPointAnnotation()
annotation.coordinate = center
self.placesMap.addAnnotation(annotation)
}
}
}
If you want to remove all of the stored locations you can say something like:
func removeStoredLocations(){
NSUserDefaults.standardUserDefaults().removeObjectForKey("locationArray")
NSUserDefaults.standardUserDefaults().synchronize()
}

Show Current Location and Update Location in MKMapView in Swift

I am learning how to use the new Swift language (only Swift, no Objective-C). To do it, I want to do a simple view with a map (MKMapView). I want to find and update the location of the user (like in the Apple Map app).
I tried this, but nothing happened:
import MapKit
import CoreLocation
class MapView : UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
}
Could you please help me?
You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last{
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
}
NOTE: If your target is iOS 8 or above, you must include the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key in your Info.plist to get the location services to work.
100% working, easy steps and tested
Import libraries:
import MapKit
import CoreLocation
set delegates:
CLLocationManagerDelegate,MKMapViewDelegate
Take variable:
let locationManager = CLLocationManager()
write this code on viewDidLoad():
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
mapView.delegate = self
mapView.mapType = .standard
mapView.isZoomEnabled = true
mapView.isScrollEnabled = true
if let coor = mapView.userLocation.location?.coordinate{
mapView.setCenter(coor, animated: true)
}
Write delegate method for location:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
mapView.mapType = MKMapType.standard
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: locValue, span: span)
mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = locValue
annotation.title = "Javed Multani"
annotation.subtitle = "current location"
mapView.addAnnotation(annotation)
//centerMap(locValue)
}
Do not forgot to set permission in info.plist
<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>
It's look like:
For swift 3 and XCode 8 I find this answer:
First, you need set privacy into info.plist. Insert string NSLocationWhenInUseUsageDescription with your description why you want get user location. For example, set string "For map in application".
Second, use this code example
#IBOutlet weak var mapView: MKMapView!
private var locationManager: CLLocationManager!
private var currentLocation: CLLocation?
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// Check for Location Services
if CLLocationManager.locationServicesEnabled() {
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
}
// MARK - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
defer { currentLocation = locations.last }
if currentLocation == nil {
// Zoom to user location
if let userLocation = locations.last {
let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
mapView.setRegion(viewRegion, animated: false)
}
}
}
Third, set User Location flag in storyboard for mapView.
MyLocation
is a Swift iOS Demo.
You can use this demo for the following:
Show the current location.
Choose other location: in this case stop tracking the location.
Add a push pin to a MKMapView(iOS) when touching.
Hi Sometimes setting the showsUserLocation in code doesn't work for some weird reason.
So try a combination of the following.
In viewDidLoad()
self.mapView.showsUserLocation = true
Go to your storyboard in Xcode, on the right panel's attribute inspector tick the User location check box, like in the attached image. run your app and you should be able to see the User location
Swift 5.1
Get Current Location and Set on MKMapView
Import libraries:
import MapKit
import CoreLocation
set delegates:
CLLocationManagerDelegate , MKMapViewDelegate
Declare variable:
let locationManager = CLLocationManager()
Write this code on viewDidLoad():
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
mapView.delegate = self
mapView.mapType = .standard
mapView.isZoomEnabled = true
mapView.isScrollEnabled = true
if let coor = mapView.userLocation.location?.coordinate{
mapView.setCenter(coor, animated: true)
}
Write delegate method for location:
func locationManager(_ manager: CLLocationManager, didUpdateLocations
locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
mapView.mapType = MKMapType.standard
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let region = MKCoordinateRegion(center: locValue, span: span)
mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = locValue
annotation.title = "You are Here"
mapView.addAnnotation(annotation)
}
Set permission in info.plist *
<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>
For Swift 2, you should change it to the following:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
You just need to set the userTrackingMode of the MKMapView. If you only want to display and track the user location and implement the same behaviour as the Apple Maps app uses, there is no reason for writing additional code.
mapView.userTrackingMode = .follow
See more at https://developer.apple.com/documentation/mapkit/mkmapview/1616208-usertrackingmode .
you have to override CLLocationManager.didUpdateLocations
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
locationManager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion (center: location,span: span)
mapView.setRegion(region, animated: true)
}
you also have to add NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription to your plist setting Result as value
In Swift 4, I had used the locationManager delegate function as defined above ..
func locationManager(manager: CLLocationManager!,
didUpdateLocations locations: [AnyObject]!) {
.. but this needed to be changed to ..
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
This came from .. https://github.com/lotfyahmed/MyLocation/blob/master/MyLocation/ViewController.swift - thanks!
mapView.showsUserLocation = true
Create UIButton and add this action
#IBAction func showCurrentLocation(_ sender: Any) {
let coordinate = mapView.userLocation.coordinate
let center = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
}

Resources