如何在 Xcode 的地图中显示我的当前位置?

How can I show my current location in maps in Xcode?

我在 Youtube 上看了一些课程,现在尝试获得实践经验。我正在从事一个涉及选项卡式应用程序的小项目,我在第一页上尝试创建一个带有显示当前位置的按钮的地图。实际上很基本。但不知何故,它就是行不通,我不知道问题出在哪里。 CodewithChris 的某个人告诉我:“我建议将你的应用程序分解成更小的组件,并确保每个组件都能正常工作,然后再继续下一个。尝试先输出您的位置,然后再将其绘制在地图等上,这样您就可以更轻松地定位错误。”我只是不明白她所说的更小的组件是什么意思。我真的很感谢我能得到的所有帮助。下面是尽可能好的代码。预先感谢您的帮助。

import UIKit

import MapKit

import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet var textFieldForAddress: UITextField!
    @IBOutlet var getDirectionsButton: UIButton!
    @IBOutlet var map: MKMapView!

    var locationManger = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManger.delegate = self
        locationManger.desiredAccuracy = kCLLocationAccuracyBest
        locationManger.requestAlwaysAuthorization()
        locationManger.requestWhenInUseAuthorization()
        locationManger.startUpdatingLocation()

        map.delegate = self

    }

    @IBAction func getDirectionsTapped(_ sender: Any) {
        getAddress()
    }


    func getAddress() {
        let geoCoder = CLGeocoder()
        geoCoder.geocodeAddressString(textFieldForAddress.text!) { (placemarks, error) in
            guard let placemarks = placemarks, let location = placemarks.first?.location
                else {
                    print("No Location Found")
                    return
            }
            print(location)
            self.mapThis(destinationCord: location.coordinate)

        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print(locations)
    }

    func mapThis(destinationCord : CLLocationCoordinate2D) {

        let souceCordinate = (locationManger.location?.coordinate)!

        let soucePlaceMark = MKPlacemark(coordinate: souceCordinate)
        let destPlaceMark = MKPlacemark(coordinate: destinationCord)

        let sourceItem = MKMapItem(placemark: soucePlaceMark)
        let destItem = MKMapItem(placemark: destPlaceMark)

        let destinationRequest = MKDirections.Request()
        destinationRequest.source = sourceItem
        destinationRequest.destination = destItem
        destinationRequest.transportType = .automobile
        destinationRequest.requestsAlternateRoutes = true

        let directions = MKDirections(request: destinationRequest)
        directions.calculate { (response, error) in
            guard let response = response else {
                if let error = error {
                    print("Something is wrong :(")
                }
                return
            }

          let route = response.routes[0]
          self.map.addOverlay(route.polyline)
          self.map.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)

        }


    }

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let render = MKPolylineRenderer(overlay: overlay as! MKPolyline)
        render.strokeColor = .blue
        return render
    }


}

好吧,这个信息出奇地难找(只是得到你自己的位置!)——即使在看完教程后我也很难找到。但基本上你缺少的是 mapView.showsUserLocation = true

这里是完整的代码,如果你需要的话...

 import UIKit
 import CoreLocation
 import MapKit

  class RadiusMapLocationViewController: UIViewController, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!
let coordinate = CLLocationCoordinate2DMake(33.97823607957177, -118.43823725357653)

var locationManager : CLLocationManager = CLLocationManager()

// Authorize use of location
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
  mapView.showsUserLocation = (status == .authorizedAlways)
}

// Entering region
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
         showAlert(withTitle: "You've entered \(region.identifier)", message: "Happy hopping!")
}

// Exiting region
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
       showAlert(withTitle: "You've exited \(region.identifier)", message: "")
}

// Creating region and notifying when exit / enter
func region(with geotification: Geotification) -> CLCircularRegion {
  let region = CLCircularRegion(center: geotification.coordinate,
    radius: geotification.radius,
    identifier: geotification.identifier)
  region.notifyOnEntry = (geotification.eventType == .onEntry)
  region.notifyOnExit = !region.notifyOnEntry
  return region
}

// Monitoring region, if not "error"
   func startMonitoring(geotification: Geotification) {
     if !CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
       showAlert(withTitle:"Error", message: "Geofencing is not supported on this device!")
       return
     }
}

   func stopMonitoring(geotification: Geotification) {
     for region in locationManager.monitoredRegions {
       guard let circularRegion = region as? CLCircularRegion,
         circularRegion.identifier == geotification.identifier else { continue }
       locationManager.stopMonitoring(for: circularRegion)
     }
   }

override func viewDidLoad() {
    super.viewDidLoad()
    mapView.delegate = self
    mapView.userTrackingMode = .follow
    mapView.showsUserLocation = true

    // Region of coordinate
    mapView.region = MKCoordinateRegion(center: coordinate, latitudinalMeters: 800, longitudinalMeters: 800)

    mapView.region = MKCoordinateRegion(center: coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000)

    let title = "Marina Bar Hop"
    let restaurantAnnotation = MKPointAnnotation()
    restaurantAnnotation.coordinate = coordinate
    restaurantAnnotation.title = title
    mapView.addAnnotation(restaurantAnnotation)

    let regionRadius = 300.0
    let circle = MKCircle(center: coordinate, radius: regionRadius)
    mapView.addOverlay(circle)

    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.delegate = self as? CLLocationManagerDelegate

    //Zoom to user location
    if let userLocation = locationManager.location?.coordinate {
        let viewRegion = MKCoordinateRegion(center: userLocation, latitudinalMeters: 200, longitudinalMeters: 200)
        mapView.setRegion(viewRegion, animated: false)
    }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let circleRenderer = MKCircleRenderer(overlay: overlay)
    circleRenderer.strokeColor = UIColor.red
    circleRenderer.lineWidth = 1.0
    return circleRenderer
    }
}

如果您需要,我这里有一些额外的功能。听起来您可能想在用户的当前位置上添加一个图钉?它也包含在此代码中。我希望这有帮助! :)

如果您想显示用户位置并让地图跟踪它,您需要在地图视图上设置两个属性 - showsUserLocationuserTrackingMode。为了使地图能够访问用户位置,您必须使用 CLocationManager.

从用户那里获得 whenInUse 授权
import MapKit

import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet var textFieldForAddress: UITextField!
    @IBOutlet var getDirectionsButton: UIButton!
    @IBOutlet var map: MKMapView!

    var locationManger = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManger.requestWhenInUseAuthorization()
        map.showsUserLocation = true
        map.userTrackingMode = .follow

    }

如果您在模拟器上 运行,那么您需要使用模拟器中的 调试 菜单模拟一个位置。