私は単に地図上にユーザーの位置を表示しようとしていますが、アプリを起動したときに、地図が現在の位置にズームする必要がありますが、地図がまったくズームしない理由はわかりません:
コードは次のとおりです。
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.showsUserLocation = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
DispatchQueue.main.async {
self.locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let location = locations.last as! CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
var region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
region.center = mapView.userLocation.coordinate
mapView.setRegion(region, animated: true)
}
私は同様の問題に直面し、何が間違っているのかを考えて4日間無駄にしました。 viewDidLoad
メソッドでこれらのコード行を作成することで最終的に解決しました:
//Zoom to user location
let noLocation = CLLocationCoordinate2D()
let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 200, 200)
mapView.setRegion(viewRegion, animated: false)
mapView.showsUserLocation = true
ViewDidLoad
メソッドで、これらの新しい変更コードを追加します。
override func viewDidLoad() {
super.viewDidLoad()
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// Check for Location Services
if (CLLocationManager.locationServicesEnabled()) {
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
}
//Zoom to user location
if let userLocation = locationManager.location?.coordinate {
let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation, 200, 200)
mapView.setRegion(viewRegion, animated: false)
}
self.locationManager = locationManager
DispatchQueue.main.async {
self.locationManager.startUpdatingLocation()
}
}
これが問題の解決に役立つことを願っています。さらに問題があればコメントを投稿してください。ありがとう
Swift 3、XCode 8.2。最初に、ヘルパー関数を書きます。
_let homeLocation = CLLocation(latitude: 37.6213, longitude: -122.3790)
let regionRadius: CLLocationDistance = 200
func centerMapOnLocation(location: CLLocation)
{
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
_
次に、viewDidLoad()
で呼び出します
_mapView.showsUserLocation = true
centerMapOnLocation(location: homeLocation)
_
これにより、ズームインした変数で指定された場所でアプリが起動します。
Swift 4.2では、このコードに変更が加えられています。現在の動作は次のとおりです。
import UIKit
import MapKit
import CoreLocation
class MapVC: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
let authorizationStatus = CLLocationManager.authorizationStatus()
let regionRadius: Double = 1000
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
locationManager.delegate = self
configureLocationServices()
}
func centerMapOnUserLocation() {
guard let coordinate = locationManager.location?.coordinate else {return}
let coordinateRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
func configureLocationServices() {
if authorizationStatus == .notDetermined {
locationManager.requestAlwaysAuthorization()
} else {
return
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
centerMapOnUserLocation()
}
}
コード:
import UIKit
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapview: MKMapView!
let locationmanager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mapview.mapType = MKMapType.standard
let location = CLLocationCoordinate2DMake(22.4651, 70.0771)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegionMake(location, span)
mapview.setRegion(region, animated: true)
let annonation = MKPointAnnotation()
annonation.coordinate = location
annonation.title = "Chandi Bazar"
annonation.subtitle = "Jamnagar"
//
mapview.addAnnotation(annonation)
self.locationmanager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled()
{
locationmanager.delegate = self
locationmanager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationmanager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
locationmanager.stopUpdatingLocation()
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
if (annotation is MKUserLocation)
{
return nil
}
let annotationidentifier = "Annotationidentifier"
var annotationview:MKAnnotationView
annotationview = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationidentifier)
let btn = UIButton(type: .detailDisclosure)
btn.addTarget(self, action: #selector(ViewController.hirenagravat(sender:)), for: .touchUpInside)
annotationview.rightCalloutAccessoryView = btn
annotationview.image = UIImage(named: "images (4).jpeg")
annotationview.canShowCallout = true
return annotationview
}
func hirenagravat(sender:UIButton)
{
let fvc = storyboard?.instantiateViewController(withIdentifier: "secondViewController") as? secondViewController
self.navigationController?.pushViewController(fvc!, animated: true)
}
地域を設定すると、マップをズームできなくなります。以下を修正します
func yourFuncName() {
//this is global var
regionHasBeenCentered = false
if !self.regionHasBeenCentered {
let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let userLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(_cllocationOfUserCurrentLocation!.coordinate.latitude, _cllocationOfUserCurrentLocation!.coordinate.longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(userLocation, span)
self.mapView.setRegion(region, animated: true)
self.regionHasBeenCentered = true
}
self.mapView.showsUserLocation = true
}
MKMapViewDelegate funcで試してください:
var isInitiallyZoomedToUserLocation: Bool = false
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
if !isInitiallyZoomedToUserLocation {
isInitiallyZoomedToUserLocation = true
mapView.showAnnotations([userLocation], animated: true)
}
}
In Swift 4.1。ズームレベルを変更するには、スパン値を変更する必要がありますMKCoordinateSpan(latitudeDelta:0.95、経度Delta:0.95)
let lat = "33.847105"
let long = "-118.2673272"
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: Double(lat)!, longitude: Double(long)!), span: MKCoordinateSpan(latitudeDelta: 0.95, longitudeDelta: 0.95))
DispatchQueue.main.async {
self.mapView(self.mapView, regionDidChangeAnimated: true)
}