Show several annotations in iOS Map - ios

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

Related

Swift mapkit not pointing at location

I have an ios application built to use mapkit and corelocation. the application works with no error but the map doesnt pin point my current location in xcode simulator and when run on an actual device it does not show the land scape and other things. just a blank map with a single road and it cannot be zoomed in or out.
below is my code
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//IF we have coordinate from manager
//let location = locations.last as CLLocation
if let location = locationManager.location?.coordinate{
userLocation = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
let region = MKCoordinateRegion(center: userLocation!, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
mapView.setRegion(region, animated: true)
mapView.removeAnnotations(mapView.annotations)
let annotation = MKPointAnnotation()
annotation.coordinate = userLocation!
annotation.title = "Me!"
mapView.addAnnotation(annotation)
}
}
additional codes would be supplied on request
Here, this Class that I use to show a Pin to location -
import UIKit
import MapKit
class ContactViewController: UIViewController,MKMapViewDelegate,CLLocationManagerDelegate {
#IBOutlet var viewBG1: UIView!
#IBOutlet var mapview: MKMapView!
override func showPinLocation() {
let annotation = MKPointAnnotation()
annotation.title = "Title"
var coordinate = CLLocationCoordinate2D()
coordinate.latitude = 28.702466
coordinate.longitude = 77.1016314
annotation.coordinate = coordinate
var region = MKCoordinateRegion()
var span = MKCoordinateSpan()
span.latitudeDelta = 0.002; // 0.0 is min value u van provide for zooming
span.longitudeDelta = 0.002
region.span=span;
region.center = coordinate; // to locate to the center
self.mapview.addAnnotation(annotation)
self.mapview.setRegion(region, animated: true)
self.mapview.regionThatFits(region)
// Do any additional setup after loading the view.
}
The simulator is doing what it is supposed to. You can change the location from the debug menu:
If you're using a storyboard, go to your map view and look for these things to edit your view:
And
You can set the map to hybrid and get streets and satellite, you can also make your mapView scalable and many other things.
If you want to set the type of view programmatically, you can implement a segmented control and do this:
#IBAction func segmentedControlAction(sender: UISegmentedControl!) {
switch (sender.selectedSegmentIndex) {
case 0:
mapView.mapType = .Standard
case 1:
mapView.mapType = .Satellite
default:
mapView.mapType = .Hybrid
}
}
And to programmatically set the UI :
self.mapView.zoomEnabled = true;
self.mapView.scrollEnabled = true;
self.mapView.userInteractionEnabled = true;

Retain map zoom level while there is a change in location

I am using a MKMapView application. but when zoom into the map to the current user location, the map zooms well. But when there is a change in current location, the map automatically zooms out to the original position where it all started. How can I retain the same level of zoom even when the location changes. Thank you.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let latestlocation:CLLocation = locations[locations.count-1]
let a = latestlocation.coordinate.latitude
let b = latestlocation.coordinate.longitude
let center = CLLocationCoordinate2D(latitude: a, longitude: b)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpanMake(0.05, 0.05))
self.mapView.setRegion(region, animated: false)
mapView.setUserTrackingMode(.follow, animated: true)
self.mapView.showsUserLocation = true
}

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

How to Center a Map on User Location IOS 9 SWIFT

Hi I have the below code which is finding the user location the radius within 1 mile:
let initialLocation = CLLocation(latitude: 51.5001524, longitude: -0.1262362)
let regionRadius: CLLocationDistance = 1000
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
func centerMapOnLocation(location:CLLocation) {
let coordianteRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordianteRegion, animated: true)
}
// Do any additional setup after loading the view, typically from a nib.
centerMapOnLocation(initialLocation)
}
This is perfect as gets a decent radius for user location, however i want to know, how do you center map on user location?
i have tried a lot of methods but i do not seem to be able to get the map to center on user location.
Any help would be much appreciated!
Thanks
MKMapView has a built in solution by using the userTrackingMode property.
mapView.userTrackingMode = .follow
I think this might help you
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)
}

Resources