mapview not centring on current users location - swift

I'm trying to centre the mapview on the users location but so far its not working. I've tried to test it on my physical device with no luck and I can't find a solution that works please help me.
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var mapView: MKMapView!
var locationManager: CLLocationManager!
let distanceSpan: Double = 500
override func viewDidLoad() {
super.viewDidLoad()
setupMapView()
}
fileprivate func setupLocationManager() {self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() == true {
if CLLocationManager.authorizationStatus() == .restricted || CLLocationManager.authorizationStatus() == .denied || CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
locationManager.desiredAccuracy = 1.0
locationManager.delegate = self
locationManager.startUpdatingLocation()
} else {
print("PLease turn on location services or GPS")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: locations[0].coordinate.latitude, longitude: locations[0].coordinate.longitude), span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
self.mapView.setRegion(region, animated: true)
}
fileprivate func setupMapView() {
let mView = MKMapView(frame: CGRect(x: 0, y: 20, width: view.frame.width, height: view.frame.height))
mView.showsUserLocation = true
view.addSubview(mView)
self.mapView = mView
}

You need to update the camera on the new location.
Read here for more information.
Basically you need to implamant the function CameraUpdate().

Related

How to replicate Snapchat Map in swift?

Lately I have been working on a little project. I would like to replicate the snapchat map program in swift. Basically I would like to display on a map a pin that indicates the position of my device in which it is installed the program. I have written some code in swift but I am not so happy with it. Any advice would be more than appreciated.
import Foundation
import CoreLocation
import MapKit
class DiscoverViewController : UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var map: MKMapView!
let locationManager: CLLocationManager! = nil
override func viewDidLoad()
{
super.viewDidLoad()
//for use in background
self.locationManager.requestAlwaysAuthorization()
//for use in foreground
self.locationManager.requestWhenInUseAuthorization()
if (CLLocationManager.locationServicesEnabled())
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations:
[AnyObject]!) { var locValue:CLLocationCoordinate2D = manager.location.coordinate
println("locations = \(localValue.latitude) \(localValue.longitude)")
let center = CLLocationCoordinate2D(latitude: locValue.latitude, longitude:
locValue.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta:
0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
var currentLocation = CLLocation()
var locationLat = currentLocation.coordinate.latitude
var locationLong = currentLocation.coordinate.longitude
println("locations = \(locationLat) \(locationLong) \
(currentLocation.coordinate.latitude) \(currentLocation.coordinate.longitude)")
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Errore while updating location" + error.localizedDescription)
}
func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager) {
<#code#>
}
}

In Swift, IBOutlet unexpectly found nil on self delegate?

This problem is absolutely driving me insane, and I've searched all over with no luck finding a solution. Please forgive what is probably a basic question...
I followed a tutorial to make a simple Geofence application. Problem is, my MKMapView keeps giving me a nil variable when I declare it, giving me the "unexpectedly found nil while unwrapping an Optional value" error.
The variable in question is mapView, and the line that's giving me an issue is mapView.delegate = self
Here's my code:
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// setup locationManager
locationManager.delegate = self
locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// setup mapView
mapView.delegate = self
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
// setup test data
setupData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// status is not determined
if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestAlwaysAuthorization()
}
// authorization were denied
else if CLLocationManager.authorizationStatus() == .denied {
showAlert(title: "Location services were previously denied. Please enable location services for this app in Settings.")
}
// we do have authorization
else if CLLocationManager.authorizationStatus() == .authorizedAlways {
locationManager.startUpdatingLocation()
}
}
func setupData() {
// check if can monitor regions
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
// region data
let title = "Weber"
let coordinate = CLLocationCoordinate2DMake(37.703026, -121.759735)
let regionRadius = 300.0
// setup region
let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude), radius: regionRadius, identifier: title)
locationManager.startMonitoring(for: region)
// setup annotation
let restaurantAnnotation = MKPointAnnotation()
restaurantAnnotation.coordinate = coordinate;
restaurantAnnotation.title = "\(title)";
mapView.addAnnotation(restaurantAnnotation)
// setup circle
let circle = MKCircle(center: coordinate, radius: regionRadius)
mapView.add(circle)
}
else {
print("System can't track regions")
}
}
// MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let circleRenderer = MKCircleRenderer(overlay: overlay)
circleRenderer.strokeColor = UIColor.blue
circleRenderer.lineWidth = 1.0
return circleRenderer
}
// MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
showAlert(title: "enter \(region.identifier)")
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
showAlert(title: "exit \(region.identifier)")
}
// MARK: - Helpers
func showAlert(title: String) {
let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}

Pressing Button Centers\Focuses MKmapView onto User's location, Swift

My code:
Please anyone ! How to make this button work !?!??!
What do i put in the #IBAction brackets to have the function i want ?
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController,MKMapViewDelegate, CLLocationManagerDelegate{
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
//==========RegionLocation : =========
// Init the zoom level
let coordinate:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 31.30, longitude: 34.45)
let span = MKCoordinateSpanMake(125, 125)
let region = MKCoordinateRegionMake(coordinate, span)
self.mapView.setRegion(region, animated: true)
//====================================\\
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//Dispose of resources that can be re created.
}
//Mark : Location
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.06, longitudeDelta: 0.06))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Errors: " + error.localizedDescription)
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let reuseID = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseID) as? MKPinAnnotationView
if(pinView == nil) {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
pinView!.rightCalloutAccessoryView = UIButton(type: UIButtonType.DetailDisclosure) as UIButton
let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare))
button.setBackgroundImage(UIImage(named: "Car"), forState: .Normal)
pinView?.leftCalloutAccessoryView = button
}
else
{
pinView!.annotation = annotation
}
return pinView
}
but when i put in the button action segment nothing happens when i press on it ?
Anyone can Guide me on How do i center the mapView onto the user location Blue dot ?
Try this
#IBAction func centerLocationButton(sender: UIButton) {
mapView.setCenterCoordinate(mapView.userLocation.coordinate, animated: true)
}
In order to use MKMapView in correct way just follow the following below code.
// `viewDidLoad` method
#IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// code for enable location seivices
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
override CLLocationManager.didUpdateLocations see below (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location.
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)
}
have a note: If your target is iOS 8, you must include the NSLocationAlwaysUsageDescription key in your Info.plist to get the location services to work.
if you want to set region in a custom way using button action just save lat and long and pass like:
#IBAction func setMap(sender: UIButton) {
let center = CLLocationCoordinate2D(latitude: lat, longitude: long)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
here is Google map guidelines. and useful tutorial
I can see what you need is to have a button to center the mapView to your current location. It is exactly same as vaibhab's answer with little modifications.
Just create to button and link the action to the viewcontroller class then copy the same code in the IBAction of the button.
#IBAction func updateCurrentLocation(_ sender: AnyObject) {
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
} else {
// Alert to enable location services on iphone first
}
}
Plus you can just add a small line of code to show the blue indicator of the location of the user. In the func locationManager.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [AnyObject]) {
self.mapView.showsUserLocation = true
}
Make sure when you are using the simulator just add a custom location from the simulators menu. Debug ---> location ----> Custom
If using a real mobile just make sure that the location services is on in the Settings---> General----> Privacy

Can't move in map view swift

I can't move or zoom the map to other locations. I used this tutorial: https://www.youtube.com/watch?v=qrdIL44T6FQ to show my location in the map. For some reason the map first zooms in very slowly (+- 30 seconds) to my location after opening the app. Then when I want to move around in the map I cant. It stays on my current location.
Here is my code:
import UIKit
import MapKit
import CoreLocation
class FirstViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
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.5, longitudeDelta: 0.5 ))
self.mapView.setRegion(region, animated: true)
self.locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Errors: " + error.localizedDescription)
}
}
Does anyone know the problem? Thanks!
Nevermind I made a mistake somewhere. This code is working fine:
import UIKit
import MapKit
import CoreLocation
class FirstViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad()
{
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Location Delegate Methods
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: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Error: " + error.localizedDescription)
}
}
For those wondering what his mistake was:
He put self.locationManager.startUpdatingLocation() in the locationManager method instead of self.locationManager.stopUpdatingLocation.

Swift 3 Current Location to Simple location between MKPolyline

Hello i have working codes for current location blue dot show and simple location pin show I want to do line between them with MKPolyline my clear codes under below.
import UIKit
import CoreLocation
import MapKit
class ShowMapViewController: UIViewController,MKMapViewDelegate ,CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
var showmapListcomming = String()
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestLocation()
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
// Show Map
var myStringArrctakes = showmapListcomming.components(separatedBy: ",")
let annotation = MKPointAnnotation()
let latitude:CLLocationDegrees = (myStringArrctakes[6] as NSString).doubleValue
let longitude:CLLocationDegrees = (myStringArrctakes[5] as NSString).doubleValue
let latDelta:CLLocationDegrees = 30
let lonDelta:CLLocationDegrees = 30
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let locations:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(locations, span)
mapView.setRegion(region, animated: false)
annotation.coordinate = locations
annotation.title = myStringArrctakes[1]
annotation.subtitle = "\(myStringArrctakes[2])"
mapView.addAnnotation(annotation)
}
// MARK: - MKMapViewDelegate methods
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView()
return annotationView
}
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.mapView.setRegion(region, animated: true)
if let location = locations.last {
print("Found User's location: \(location)")
print("Latitude: \(location.coordinate.latitude) Longitude: \(location.coordinate.longitude)")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: NSError) {
print("Failed to find user's location: \(error.localizedDescription)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I think easy but I didn't resolve it. Im waiting your ideas , I think will be help many people so in swift 3 I didn't find anything like this on web.
Thanks