Saving map pins to array, Swift - ios

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()
}

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 View not zooming in to users location

In my application I have a MKMapKit view and when my application starts, if the user allows location services, I want the Map to zoom into the user's location. The code I wrote is:
override func viewDidLoad() {
super.viewDidLoad()
mapKitView.delegate = self
mapKitView.showsUserLocation = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
if (CLLocationManager.locationServicesEnabled()) {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
}
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
DispatchQueue.main.async {
self.locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let noLocation = CLLocationCoordinate2D()
let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 200, 200)
mapKitView.setRegion(viewRegion, animated: false)
}
In my app, it shows the users location, but does not animate and zoom in.
Use the user's location to calculate the view region and change the animated parameter to true:
if let location = mapKitView.userLocation.location {
let viewRegion = MKCoordinateRegionMakeWithDistance(location, 200, 200)
mapKitView.setRegion(viewRegion, animated: true)
}
In Swift 3.0, try my code in your didUpdateLocation method.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
//get location cordinate
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print(locValue)
//set updating location stop
locationManager.stopUpdatingLocation()
let location = locations.last! as CLLocation//create object of CLLocation
//get location cordinate
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
//set map zooming using region
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
}
I hope it's work #Rahul Bir
In Swift 3.0 you should use this code if you want to zoom map Kit on the starting view of the map view.
var zoomIn = false
var zoomAnnotation:MKAnnotation
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if let annotation = zoomAnnotation where zoomIn == true {
let region = MKCoordinateRegion(center: zoomAnnotation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.075, longitudeDelta: 0.075))
mapView.setRegion(region, animated: true)
zoomIn = false
}
}

Show several annotations in iOS Map

I am trying to show user's current location and users nearby the area.
I am doing to show user's
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude:location!.coordinate.latitude ,longitude : location!.coordinate.longitude )
let span = MKCoordinateSpanMake(0.01,0.01 )
let region = MKCoordinateRegion(center: center, span: span)
self.mapView.setRegion(region, animated: true)
self.manager.stopUpdatingLocation()
}
Plotting near by users
plotUsersonGraph(lat,longitude:long,title:"Apple HQ",subtitle:"Welcome to Apple")
func plotUsersonGraph(latitude:Double,longitude:Double,title:String,subtitle:String){
let HQlocation = CLLocationCoordinate2DMake(latitude, longitude)
let span = MKCoordinateSpanMake(0.01, 0.01)
let region = MKCoordinateRegion(center: HQlocation, span: span)
// self.mapView.setRegion(region, animated: true)**THIS IS CAUSING PROBLEM**
let annotation = MKPointAnnotation()
annotation.coordinate = HQlocation
annotation.title = title
annotation.subtitle = subtitle
self.mapView.addAnnotation(annotation)
}
I am able to view both the locations individually but I am unable to merge both of them together. plotUsersonGraph will add multiple users on the graph simultaneously.
This is how I achieved it
Added
self.mapView.showsUserLocation = true
inside
func plotUsersonGraph(latitude:Double,longitude:Double,title:String,subtitle:String){
}

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)
}

Adding userlocation annotation by tap

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)
}
}

Resources