Wie kann ich den aktuellen Standort des Benutzers speichern und den Standort auch auf einer Karte anzeigen?
Ich kann vordefinierte Koordinaten auf einer Karte anzeigen, ich weiß nur nicht, wie ich Informationen vom Gerät erhalten soll.
Außerdem weiß ich, dass ich einige Elemente in eine Plist einfügen muss. Wie kann ich das machen?
Um den aktuellen Standort eines Benutzers abzurufen, müssen Sie Folgendes angeben:
let locationManager = CLLocationManager()
In viewDidLoad()
müssen Sie die CLLocationManager
-Klasse wie folgt instanziieren:
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
Dann können Sie in der CLLocationManagerDelegate-Methode die aktuellen Standortkoordinaten des Benutzers abrufen:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
In der info.plist müssen Sie NSLocationAlwaysUsageDescription
Und Ihre benutzerdefinierte Warnmeldung wie hinzufügen. AppName (Demo-App) möchte Ihren aktuellen Standort verwenden.
sie sollten diese Schritte ausführen:
CoreLocation.framework
zu BuildPhases hinzufügen -> Binäre mit Bibliotheken verknüpfen (ab XCode 7.2.1 nicht mehr erforderlich)CoreLocation
in Ihre Klasse - höchstwahrscheinlich ViewController.SwiftCLLocationManagerDelegate
hinzuNSLocationWhenInUseUsageDescription
und NSLocationAlwaysUsageDescription
zu plist hinzuinit location manager:
locationManager = CLLocationManager()
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
benutzerort erhalten durch:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
So bin ich
den aktuellen Standort abrufen und auf der Karte in Swift 2.0 anzeigen
Stellen Sie sicher, dass Sie CoreLocation und MapKit Framework zu Ihrem Projekt hinzugefügt haben. (Dies ist bei XCode 7.2.1 nicht erforderlich.)
import Foundation
import CoreLocation
import MapKit
class DiscoverViewController : 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()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
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)
}
}
Hier ist der Ergebnisbildschirm
NSLocationWhenInUseUsageDescription = Fordern Sie die Berechtigung an, den Standortdienst zu verwenden, wenn sich die Apps im Hintergrund befinden. in deiner plist datei.
Wenn dies funktioniert, stimmen Sie bitte die Antwort ab.
Erster Import der Corelocation- und MapKit-Bibliothek:
import MapKit
import CoreLocation
erben Sie von CLLocationManagerDelegate an unsere Klasse
class ViewController: UIViewController, CLLocationManagerDelegate
erstellen Sie eine locationManager-Variable. Dies sind Ihre Standortdaten
var locationManager = CLLocationManager()
erstellen Sie eine Funktion, um die Standortinformationen abzurufen. Geben Sie dabei genau diese Syntax an:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
erstellen Sie in Ihrer Funktion eine Konstante für den aktuellen Standort des Benutzers
let userLocation:CLLocation = locations[0] as CLLocation // note that locations is same as the one in the function declaration
die Aktualisierung des Standorts wird angehalten. Dadurch wird verhindert, dass Ihr Gerät das Fenster ständig ändert, um sich während des Verschiebens zu zentrieren.
manager.stopUpdatingLocation()
benutzer koordinieren von userLocatin, das Sie gerade definiert haben:
let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)
definieren Sie, wie vergrößert Ihre Karte sein soll:
let span = MKCoordinateSpanMake(0.2,0.2)
kombiniere diese beiden, um die Region zu erhalten:
let region = MKCoordinateRegion(center: coordinations, span: span)//this basically tells your map where to look and where from what distance
legen Sie nun die Region fest und legen Sie fest, ob Sie mit Animation dorthin gehen möchten oder nicht
mapView.setRegion(region, animated: true)
schließen Sie Ihre Funktion }
von Ihrer Schaltfläche oder auf eine andere Weise, wie Sie locationManagerDeleget auf "selbst" setzen möchten
jetzt den Ort anzeigen lassen
genauigkeit angeben
locationManager.desiredAccuracy = kCLLocationAccuracyBest
genehmigen:
locationManager.requestWhenInUseAuthorization()
Um den Standortdienst autorisieren zu können, müssen Sie diese beiden Zeilen zu Ihrer Liste hinzufügen.
standort abrufen:
locationManager.startUpdatingLocation()
zeigen Sie es dem Benutzer:
mapView.showsUserLocation = true
Dies ist mein vollständiger Code:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func locateMe(sender: UIBarButtonItem) {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
manager.stopUpdatingLocation()
let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.2,0.2)
let region = MKCoordinateRegion(center: coordinations, span: span)
mapView.setRegion(region, animated: true)
}
}
Swift 3.0
Wenn Sie den Standort des Benutzers nicht in der Karte anzeigen möchten, sondern nur in der Firebase oder an einem anderen Ort speichern möchten, befolgen Sie diese Schritte.
import MapKit
import CoreLocation
Verwenden Sie jetzt CLLocationManagerDelegate für Ihr VC, und Sie müssen die letzten drei unten aufgeführten Methoden überschreiben. Sie können sehen, wie die requestLocation () -Methode Sie den aktuellen Benutzerstandort mithilfe dieser Methoden abruft.
class MyVc: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
isAuthorizedtoGetUserLocation()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
}
}
//if we have no permission to access user location, then ask user for permission.
func isAuthorizedtoGetUserLocation() {
if CLLocationManager.authorizationStatus() != .authorizedWhenInUse {
locationManager.requestWhenInUseAuthorization()
}
}
//this method will be called each time when a user change his location access preference.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
print("User allowed us to access location")
//do whatever init activities here.
}
}
//this method is called by the framework on locationManager.requestLocation();
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did location updates is called")
//store the user location here to firebase or somewhere
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Did location updates is called but failed getting location \(error)")
}
}
Jetzt können Sie den folgenden Anruf mit einem Code versehen, sobald sich der Benutzer bei Ihrer App angemeldet hat. Wenn requestLocation () aufgerufen wird, wird darüber hinaus didUpdateLocations aufgerufen, und Sie können den Speicherort in Firebase oder anderswo speichern.
if CLLocationManager.locationServicesEnabled() {
locationManager.requestLocation();
}
wenn Sie GeoFire verwenden, können Sie oben in der didUpdateLocations-Methode den Ort wie unten speichern
geoFire?.setLocation(locations.first, forKey: uid) where uid is the user id who logged in to the app. I think you will know how to get UID based on your app sign in implementation.
Zu guter Letzt gehen Sie zu Ihrer Info.plist und aktivieren Sie "Privacy -Location in Use Usage Description".
Wenn Sie den Simulator zum Testen verwenden, erhalten Sie immer einen benutzerdefinierten Speicherort, den Sie in Simulator -> Debug -> Speicherort konfiguriert haben.
Bibliothek importieren wie:
import CoreLocation
stellvertreter einstellen:
CLLocationManagerDelegate
Nehmen Sie eine Variable wie:
var locationManager:CLLocationManager!
Bei viewDidLoad () schreibe diesen hübschen Code:
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
Schreibe CLLocation-Delegatmethoden:
//MARK: - location delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation :CLLocation = locations[0] as CLLocation
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
self.labelLat.text = "\(userLocation.coordinate.latitude)"
self.labelLongi.text = "\(userLocation.coordinate.longitude)"
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
if (error != nil){
print("error in reverseGeocode")
}
let placemark = placemarks! as [CLPlacemark]
if placemark.count>0{
let placemark = placemarks![0]
print(placemark.locality!)
print(placemark.administrativeArea!)
print(placemark.country!)
self.labelAdd.text = "\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)"
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error \(error)")
}
Legen Sie nun die Berechtigung für den Zugriff auf den Speicherort fest, und fügen Sie diese Schlüsselwerte in Ihre Datei info.plist ein
<key>NSLocationAlwaysUsageDescription</key>
<string>Will you allow this app to always know your location?</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
100% arbeiten ohne Probleme. GEPRÜFT
fügen Sie zunächst zwei Frameworks in Ihr Projekt ein
1: MapKit
2: Corelocation (ab XCode 7.2.1 nicht mehr erforderlich)
Definieren Sie in Ihrer Klasse
var manager:CLLocationManager!
var myLocations: [CLLocation] = []
dann in der viewDidLoad-Methode diesen Code
manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
//Setup our Map View
mapobj.showsUserLocation = true
vergessen Sie nicht, diese beiden Werte in die Plist-Datei einzufügen
1: NSLocationWhenInUseUsageDescription
2: NSLocationAlwaysUsageDescription
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization();
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
else{
print("Location service disabled");
}
}
Dies ist Ihre Ansichtsmethode und in der ViewController-Klasse ist auch die MapStart-Aktualisierungsmethode wie folgt enthalten
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue : CLLocationCoordinate2D = manager.location.coordinate;
let span2 = MKCoordinateSpanMake(1, 1)
let long = locValue.longitude;
let lat = locValue.latitude;
print(long);
print(lat);
let loadlocation = CLLocationCoordinate2D(
latitude: lat, longitude: long
)
mapView.centerCoordinate = loadlocation;
locationManager.stopUpdatingLocation();
}
Auch nicht vergessen, CoreLocation.FrameWork und MapKit.Framework in Ihrem Projekt hinzuzufügen (ab XCode 7.2.1 nicht mehr erforderlich)
import CoreLocation
import UIKit
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status != .authorizedWhenInUse {return}
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
let locValue: CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
}
Da der Aufruf von requestWhenInUseAuthorization
asynchron ist, ruft die App die Funktion locationManager
auf, nachdem der Benutzer die Berechtigung erteilt oder abgelehnt hat. Daher ist es angebracht, Ihren Standort mit der Berechtigung des Benutzers in diese Funktion einzugeben. Dies ist das beste Tutorial, das ich dazu gefunden habe .
Verwendungszweck:
Feld in Klasse definieren
let getLocation = GetLocation()
Verwendung in Funktion der Klasse durch einfachen Code:
getLocation.run {
if let location = $0 {
print("location = \(location.coordinate.latitude) \(location.coordinate.longitude)")
} else {
print("Get Location failed \(getLocation.didFailWithError)")
}
}
Klasse:
import CoreLocation
public class GetLocation: NSObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
var locationCallback: ((CLLocation?) -> Void)!
var locationServicesEnabled = false
var didFailWithError: Error?
public func run(callback: @escaping (CLLocation?) -> Void) {
locationCallback = callback
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
manager.requestWhenInUseAuthorization()
locationServicesEnabled = CLLocationManager.locationServicesEnabled()
if locationServicesEnabled { manager.startUpdatingLocation() }
else { locationCallback(nil) }
}
public func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
locationCallback(locations.last!)
manager.stopUpdatingLocation()
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
didFailWithError = error
locationCallback(nil)
manager.stopUpdatingLocation()
}
deinit {
manager.stopUpdatingLocation()
}
}
// its with strongboard
@IBOutlet weak var mapView: MKMapView!
//12.9767415,77.6903967 - exact location latitude n longitude location
let cooridinate = CLLocationCoordinate2D(latitude: 12.9767415 , longitude: 77.6903967)
let spanDegree = MKCoordinateSpan(latitudeDelta: 0.2,longitudeDelta: 0.2)
let region = MKCoordinateRegion(center: cooridinate , span: spanDegree)
mapView.setRegion(region, animated: true)
100% arbeiten in iOS Swift 4 von: Parmar Sajjad
Schritt 1: Gehen Sie zu GoogleDeveloper Api Console und erstellen Sie Ihren ApiKey
Schritt 2: Springen Sie zum Projekt Cocoapods GoogleMaps Pod
schritt 3: Gehen Sie zu AppDelegate.Swift und importieren Sie GoogleMaps und
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
GMSServices.provideAPIKey("ApiKey")
return true
}
schritt 4: UIKit importieren GoogleMaps importieren Klasse ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapview: UIView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManagerSetting()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManagerSetting() {
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.showCurrentLocationonMap()
self.locationManager.stopUpdatingLocation()
}
func showCurrentLocationonMap() {
let
cameraposition = GMSCameraPosition.camera(withLatitude: (self.locationManager.location?.coordinate.latitude)! , longitude: (self.locationManager.location?.coordinate.longitude)!, zoom: 18)
let mapviewposition = GMSMapView.map(withFrame: CGRect(x: 0, y: 0, width: self.mapview.frame.size.width, height: self.mapview.frame.size.height), camera: cameraposition)
mapviewposition.settings.myLocationButton = true
mapviewposition.isMyLocationEnabled = true
let marker = GMSMarker()
marker.position = cameraposition.target
marker.snippet = "Macczeb Technologies"
marker.appearAnimation = GMSMarkerAnimation.pop
marker.map = mapviewposition
self.mapview.addSubview(mapviewposition)
}
}
schritt 5: Öffne die info.plist-Datei und füge unter Datenschutz hinzu - Standort bei Verwendung Beschreibung der Verwendung ... unter einem Basisnamen der Haupt-Storyboard-Datei
schritt 6: laufen
hier ist ein Beispiel zum Kopieren und Einfügen, das für mich funktioniert hat.
http://swiftdeveloperblog.com/code-examples/determine-users-current-location-example-in-Swift/
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
determineMyCurrentLocation()
}
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
// Call stopUpdatingLocation() to stop listening for location updates,
// other wise this function will be called every time when user location changes.
// manager.stopUpdatingLocation()
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
}