Change MKMapView's Zoom - Swift 4 - ios

I using Apple's MapKit and MKMapView to show a location on screen. The function I am using is:
func displayLocation() {
locationMap.setRegion(MKCoordinateRegion(center: CLLocationCoordinate2DMake(userConnected.siteConnectedLat!, userConnected.siteConnectedLong!), span: MKCoordinateSpanMake(0.05, 0.05)), animated: true)
let locationPin = CLLocationCoordinate2D(latitude: userConnected.siteConnectedLat!, longitude: userConnected.siteConnectedLong!)
let annotation = MKPointAnnotation()
annotation.coordinate = locationPin
locationMap.addAnnotation(annotation)
locationMap.showAnnotations([annotation], animated: true)
}
Is is then called in the viewDidLoad method of the View Controller. Apple's documentation says that the span should change the zoom but even changing the span is putting minimum effect on the map. I want it to be zoomed out enough so that we can clearly see like 3-4 European countries, i.e, a significant amount of zoom-out.
This is what my map looks like in simulator:
This is how it looks like after I press enlarge:

You need to set the region of the map in viewDidAppear, not viewDidLoad. When viewDidLoad is called, the map view has just been loaded - the map hasn't been rendered yet, so you can't set its region.
Another thing to change is the span. (0.05, 0.05) seems too small a span to show 3-4 countries. You should try something bigger, like (5, 5). Remember that these numbers represent in degrees the width and height of the map region.

Related

How do i restrict panning and restrict zooming out of a certain area of apple maps in MapKit?

I am currently making an app with a map that should focus on a certain location only. I would like the user to not be able to zoom out or pan out of this area so they can keep their focus on the image overlay that i have put over this area.
In order to get the app to start off from the location that i want and not some random map, I used a tutorial from Ray Wenderlich: https://www.raywenderlich.com/425-mapkit-tutorial-overlay-views
How would I acoomplish my task based on the code that is written in the tutorial above? I have completed the tutorial, so I am looking for help in adding any code and identifying where and what kind of code to put.
I found other tutorials on this topic unhelpful because they were for other map types like Google maps or MapBox. The apple website about MapKit and MaximumZ does not help me very much either.
I am a beginner in XCode and Swift, and have only had little bit of experience in Python previously. I was hoping limiting the zoom and user access to parts of the maps would be easier...
override func viewDidLoad() {
super.viewDidLoad()
let latDelta = park.overlayTopLeftCoordinate.latitude -
park.overlayBottomRightCoordinate.latitude
// Think of a span as a tv size, measure from one corner to another
let span = MKCoordinateSpanMake(fabs(latDelta), 0.0)
let region = MKCoordinateRegionMake(park.midCoordinate, span)
mapView.region = region
}
This is what I have so far for getting the app to startup on the location that I want, using a rectangle that bounds the area that I am looking to restrict the user to.
The MKMapView has a delegate MKMapViewDelegate. This protocol has a function called:
func mapViewDidChangeVisibleRegion(_:)
This method is called whenever the user scrolls or zooms the map. In this method you can specify the behavior of the map. You can, for instance set a specific region that you want the map to zoom into and specify the maximum level of zoom allowed.
In the function mapViewDidChangeVisibleRegion(_:) you can then check to what latitudeDelta and longitudeDelta the map can zoom into. If the delta's go below or above a certain level you can lock the zooming by setting the region with something like this:
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
if mapView.region.span.latitudeDelta < 0.4 {
regionSpan = MKCoordinateSpan(latitudeDelta: 0.4, longitudeDelta: 0.5)
let mapRegion = MKCoordinateRegion(center: self.centerCoordinate, span: self.regionSpan)
self.trackMapView.setRegion(mapRegion, animated: true)
}
}

Why is my map view zooming in when I add annotations?

I have a MKMapView that I configure with:
static let STARTING_MAP_RANGE: Double = 1000 // meters
. . .
let region: MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(location,
MapViewController.STARTING_MAP_RANGE,
MapViewController.STARTING_MAP_RANGE)
mapView.setRegion(region, animated: true)
I add an annotation for the current location and it all looks fine. When I add an annotation for other points in the visible region, the MKMapView zooms in to the minimum area needed to show all the annotations.
The weird thing is that I tried to figure out where this was happening by printing out the bottom left and top right latitude and longitude like this:
private func printMapRegion(caller: String)
{
let mapRect = mapView.visibleMapRect;
let bottomLeft = MKCoordinateForMapPoint(MKMapPointMake(mapRect.origin.x, MKMapRectGetMaxY(mapRect)))
let topRight = MKCoordinateForMapPoint(MKMapPointMake(MKMapRectGetMaxX(mapRect), mapRect.origin.y))
print("\(caller): (\(bottomLeft.latitude),\(bottomLeft.longitude)) -- (\(topRight.latitude),\(topRight.longitude))")
}
When I run this before and after setting the annotations, I get identical values, despite seeing the map zoom on the screen (both in the simulator and my iPhone).
I added a refresh button to reset the map. It works as far as zooming the map out, but it also reports that the bottom left and top right coordinates are the same before and after zooming.
Is there something wrong with my understanding of visibleMapRect?
I found that the reason for the zooming is that I was adding the annotations like this:
mapView.removeAnnotations(mapView.annotations)
mapView.addAnnotations(annotations)
mapView.showAnnotations(mapView.annotations, animated: true)
Removing the call to showAnnotations eliminated the problem. I'm still curious as to why visibleMapRect is reporting the same bounding coordinates after the visible zoom.

Swift mkmapview get zoom level, width or radius of visible map area from latitude longitude delta

I am in a confusion, on how to get a zoom level and radius of a visible area of the map (using mapkit mapview).
Here is what I am looking for (either of them or both, as needed) -
Zoom level, is to see at what level of the map is being shown to the users and with that information, I want to display the custom pins in the visible area. If zoom level is high, I need to show the actual logos of some commerce stores as pins. If zoom level is low, I need to show colored dots instead of logos.
As of now, I am using let updatedRadius = (mapView.camera.altitude)/1000 to get altitude of the camera, and if the updatedRadius value is > 25.0, I am showing colored dots. Below 25.0, I show the logos. I am doing this in regionDidChanged
Is this approach correct?
Radius, is to send it as a parameter to my REST API to fetch the list of places within that radius. When user zooms out on the map, visible area increases and so the REST API needs bigger radius to return the places covered in that area.
Ultimately, what should happen is, whenever user zooms out, then the radius changes. I need to send this changed radius to my REST to get an updated list.
What are latitude longtitude deltas, can we get radius/width of visible area using these values?
let latitudeDeltaVal = mapView.region.span.latitudeDelta
let longitudeDeltaVal = mapView.region.span.longitudeDelta
Can someone throw some light on what needs to be done please?
Since you need to call the api when the region changes you need to calculate the radius in mapView's delegate function, RegionDidChange.
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let centralLocation = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude)
self.centralLocationCoordinate = mapView.centerCoordinate
print("Radius - \(self.getRadius(centralLocation))")
}
func getRadius(centralLocation: CLLocation) -> Double{
let topCentralLat:Double = centralLocation.coordinate.latitude - mapView.region.span.latitudeDelta/2
let topCentralLocation = CLLocation(latitude: topCentralLat, longitude: centralLocation.coordinate.longitude)
let radius = centralLocation.distanceFromLocation(topCentralLocation)
return radius / 1000.0 // to convert radius to meters
}
To account for both landscape and portrait orientations, and/or situations where the map orientation is close to Northeast, Northwest, Southwest, Southeast, and to enclose the full screen up to the corners, one should consider both latitudeDelta and longitudeDelta:
func getRadius() -> Double{
let centralLocation = CLLocation(latitude: mapView.region.center.latitude, longitude: mapView.region.center.longitude)
let cornerOfMap = CLLocation(latitude: centralLocation.coordinate.latitude + mapView.region.span.latitudeDelta , longitude: centralLocation.coordinate.longitude + mapView.region.span.longitudeDelta)
let radius = centralLocation.distance(from: cornerOfMap)
return radius / 1000.0 // to convert radius to meters
}

How do I achieve the maximum zoom level in iOS mapKit?

I'm aware of this post: How to get to the max zoomlevel on iOS MKMapView
And it seems to be exactly what I need to solve the problem, however, the technique does not work for me.
If I set the eyeAltitude at 50, or even 100, I get the same map zoom returned. However, once the map is displayed, I can pinch to zoom to the desired zoom level. is there a solution to programmatically achieve the pinched in zoom level at the initial load of the map view?
EDIT: I've tried using setRegion but the problem seems to be related to using .satelliteFlyover specifically. I need to use .satelliteFlyover due to the difference in image quality.
Further EDIT: I've also discovered that the simulator seems to give a different 'native zoom' than when it runs on my device. I hope someone reads this that can provide insight!!
the code I'm using is:
let greenLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(CLLocationDegrees(greenX),CLLocationDegrees(greenY))
let altitude:CLLocationDistance = 80
self.greenMap.mapType = .satelliteFlyover
let camera = MKMapCamera(lookingAtCenter: greenLocation, fromEyeCoordinate: greenLocation, eyeAltitude: altitude)
self.greenMap.setCamera(camera, animated: true)
You can set region to make map view scale to fit. Use this function.
open func setRegion(_ region: MKCoordinateRegion, animated: Bool)
Here is the sample code.
let map = MKMapView()
let center = CLLocationCoordinate2D(latitude: 115, longitude: 24)
let span = MKCoordinateSpan(latitudeDelta: 0.003, longitudeDelta: 0.003)
let region = MKCoordinateRegion(center: center, span: span)
map.setRegion(region, animated: false)
I solved this by... using a different SDK for mapping. What I found through continued testing is that appleMaps doesn't always have the imagery down to the specific zoom level, and seems to get tripped up when you zoom in ultra close. on some locations it would zoom perfectly, and others it would not - an inconsistency that as a developer you may want to be weary of. googleMap had higher quality imagery and no issues with zoom consistency.

MKMapView Doesn't Show Whole World At Once

I'm working on an application that tracks movement in Swift, for traveling from point A: locationOne, to point B: locationTwo. The MapView should display both points on the map, centered in between them.
I implemented a function to determine the center location as per this link, though I had to modify it to function in Swift. The function is called findCenterPoint.
Then, I set the mapView's region to an MKCoordinateRegion. This region is created like so: let region = MKCoordinateRegionMakeWithDistance(center, 2*distanceOne, 2*distanceTwo), and then the mapView's region is set like this: mapView.setRegion(region, animated: false)
I multiply the distance by 2 so that we have a margin on the sides of the two locations (the annotation for locationOne, and locationTwo: the user location)
Here's the problem: If the two points are very far away, i.e. New York and somewhere in Australia (let's just say general Australia) the app can't display both points, because they don't fit on the mapView. So instead, only one pin is visible, because the other one is off the screen.
Screenshots of problem
I need both of those points to show up without scrolling around the map.
I also have a degreesToRadians function which is used in the code below.
TL;DR: My app's mapView isn't big enough to fit and display two far away points on the map, and it is already zoomed out to the max.
Here's the actual code:
var center = findCenterPoint(firstLocation.coordinate, locTwo: placemark.coordinate)
let earthRadius: Double = 6371000
distance = degreesToRadians(placemark.coordinate.latitude - firstLocation.coordinate.latitude)
lonDistance = degreesToRadians(placemark.coordinate.longitude - firstLocation.coordinate.longitude)
let region = MKCoordinateRegionMakeWithDistance(center, earthRadius*distance, earthRadius*lonDistance)
mapView.setRegion(region, animated: false)

Resources