How to get a reliable rect of the whole mapview (not just visible) with Mapbox? - ios

So I've been struggling with this for some time. I wish to know the CGRect of the whole map. The issue I am facing right now is that due to the wrapping of the map, the x of the top-left coordinate keeps switching between a negative and a positive value as I move around the map. This results in the width of the map also changing.
I tried restricting the camera bounds to prevent wrapping and it does that job perfectly, but it still doesn't help with x switching between positive/negative as I move around the map.
let extremeBounds = CoordinateBounds(
southwest: CLLocationCoordinate2D(latitude: -62.59334083012023, longitude: -141.328125),
northeast: CLLocationCoordinate2D(latitude: 82.85338229176081, longitude: 167.34375)
)
try? view.mapboxMap.setCameraBounds(with: CameraBoundsOptions(bounds: extremeBounds))
This is how I am calculating the rect on cameraChange:
mapView.mapboxMap.rect(for: self.extremeBounds)
Is there an official way of disabling the wrapping of the map so that the northwest coordinate always appears at the top left side of the map? Or maybe my approach is incorrect and there's an easier way of finding out the rect of the map?

you can try setting ConstrainModeto widthAndHeight, by default this value is heightOnly-> only y axis is constrained.
let mapInitOptions = MapInitOptions(mapOptions: MapOptions(constrainMode: .widthAndHeight))
let mapView = MapView(frame: view.bounds, mapInitOptions: mapInitOptions)

Related

Get google map currently rotated angle by user in iOS

I am using google map in the application. When I do not rotate map everything works fine. But when I rotate map I am getting problem as shown in image. To solve that I need to get the google map currently rotated angle by the user. I need to get this so that I can place the marker back on the map at the same angle. Currently my map angle after rotation and my overlay seems to be different after placing plan image on map even when I am getting correct top left & bottom right corner coordinates.
My code
let topCoordinate = CLLocationCoordinate2D(latitude: topLattitude, longitude: topLongitude)//top
let bottomCoordinate = CLLocationCoordinate2D(latitude: bottomLattitude, longitude: bottomLongitude)//bottom
overlayBounds = GMSCoordinateBounds(coordinate: topCoordinate, coordinate:
bottomCoordinate)
let overlay = GMSGroundOverlay(bounds: overlayBounds, icon: planImage)
overlay.map = mapView
GMSMapViewDelegate
Bearing of the camera, in degrees clockwise from true north.
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
print(position.bearing)
}
I have solved my problem by changing the overlay method as
let zoomLevel = (object["image_zoom_level"] as? NSString)?.doubleValue
let overlay = GMSGroundOverlay(position: centreCoordinate, icon: planImage, zoomLevel: CGFloat(zoomLevel!))
overlay.map = mapView
if let angle = (object["rotation_angle"] as? NSString)?.doubleValue{
overlay.bearing = angle
}
Instead of using Overlay bounds I have just used center coordinate and placed overlay image using image zoom level and rotation angle. By this, my image is placing in proper angle and at a proper place. This works fine if the Image size is correct as you want place and the center point is accurate and precise.

Calculate bearing in MKMapView gives wrong value while crossing 180 meridian

I need to draw lines to demonstrate transportation of goods on apple maps. To clarify start- and end-point, I draw a little arrowhead on the destination side.The arrowhead is drawn separately but it is reversed in one case.
>-->-->-->-
instead of
<--<--<--<-
I am using MKMapView and MKPolyline to draw lines. I am using MKOverlay to add direction arrows. The steps I follow are,
calculate bearing of
Source : CLLocationCoordinate2D(latitude: -33.8392932, longitude: 151.21519799999999)
Destination: CLLocationCoordinate2D(latitude: 39.645516999999998, longitude: -104.598724)
using the following function
open static func getDirectionOf( _ supplyLineWithCoordinates: [CLLocationCoordinate2D]) -> CGFloat {
guard let sourceCoordniate = supplyLineWithCoordinates.first,
let destinationCoordniate = supplyLineWithCoordinates.last else {
fatalError("Coordinates of supply line not found")
}
let sourcePoint: MKMapPoint = MKMapPointForCoordinate(sourceCoordniate)
let destinationPoint: MKMapPoint = MKMapPointForCoordinate(destinationCoordniate)
let x: Double = destinationPoint.x - sourcePoint.x
let y: Double = destinationPoint.y - sourcePoint.y
var arrowDirection = CGFloat(fmod(atan2(y, x), 360.0))
if arrowDirection < 0.0 {
arrowDirection += 2 * .pi
}
return arrowDirection
}
Rotate the arrow image and add it as the map overlay. The directions are calculated correctly in most of the cases, however, when I select the line shown below the direction is displayed 180 opposite. It starts from Sydney, Australia and ends in Denver, US
When trying to display the region with this two locations in mapView.setVisibleMapRect these region is not displayed, mapview tries to display region starting from Sydney (Australia) to Denver(US) through Asia and Europe, while it should display the map area I have attached above. If you have suggestions for optimisation, feel free to mention it.
I think this might be the reason, the direction should be calculated along the red line but it being calculated along the green line. Both lines are drawn by connecting same location coordinates in map. Any known workaround for this?
I solved it in a dirty way by converting coordinate to CGPoint and then calculating bearing between Points.
let destinationPoint = mapView.convert(destination, toPointTo: nil)
let sourcePoint = mapView.convert(source, toPointTo: nil)
let bearing = atan2(sourcePoint.y - destinationPoint.y, sourcePoint.x - destinationPoint.x) - .pi
Caution: This calculation will go wrong when map is rotated

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.

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)

Best practice for using lat/long within a UIView (not MKMapView)

Basically i have a list of POI's (name,lat,long) and i want to draw them on the UIView, relative to my current lat/long. I'm looking for some best practice for mapping these POI (lat/long) to a UIView.
I don't want to use MKMapView (no need for displaying map-data).
I was reading:
http://developer.apple.com/library/ios/#documentation/general/conceptual/Devpedia-CocoaApp/CoordinateSystem.html
But I'm clueless how i get from a CLLocation to a (x,y) on my UIView. I only want to draw those POI's around my current location. So, for example if my screen would represent a 20 by 30 KM region, how do i map my POI's to their corresponding (x,y) coordinates?
Thanks.
What you're doing is a little strange, but you can convert latitude/longitude to a CGPoint-like struct called an MKMapPoint. An MKMapPoint has an x and y value which correspond to points on a map. Imagine if you laid out a flat map of the world, and 0,0 was the top left. MKMapPoint is a point on that map using that coordinate system.
Use the function MKMapPointForCoordinate() to convert a CLLocationCoordinate2D to an MKMapPoint
MKMapPoint myMapPoint = MKMapPointForCoordinate(myLocationCoordinate);
When you get the list of points, you'll have to do something like finding the max and min x and y values, then fitting all the points into your view using those values, otherwise you'll end up with a load of very close points in one place in your view.
My guess is that, for a 20KM by 30KM region, you can consider the earth to be flat and there fore linearly extrapolate the coordinates. I am sure you can google and find out as to how much distance is a difference in 0.00001 in latitude and longitude.
So if you have 20Km to be represented on X axis, and your current location is 30.1234567 in latitude, and 0.0000001 is 1 km then you can put your coordinate in the center of the screen and 30.1234557 as the left most X coordinate and so on.
I am not trying to provide an answer here, but just trying to think out loud, because I wanted to do some thing similar as well and did it as an Internet based app (without display though), where given two coordinates, I had to find the distance between them.
There are many (many) different approaches to modelling the planet and translating 3D coordinates onto a 2D surface, and the errors introduced by the various methods vary depending on what part of the globe you are. This question seems to cover most of what you are after though:
Converting Longitude & Latitude to X Y on a map with Calibration points
I think its best way (correctly work for Mercator projection map):
extension UIView
{
func addLocation(coordinate: CLLocationCoordinate2D)
{
// max MKMapPoint values
let maxY = Double(267995781)
let maxX = Double(268435456)
let mapPoint = MKMapPointForCoordinate(coordinate)
let normalizatePointX = CGFloat(mapPoint.x / maxX)
let normalizatePointY = CGFloat(mapPoint.y / maxY)
let pointView = UIView(frame: CGRectMake(0, 0, 5, 5))
pointView.center = CGPointMake(normalizatePointX * frame.width, normalizatePointY * frame.height)
pointView.backgroundColor = UIColor.blueColor()
addSubview(pointView)
}
}
My simple project for adding coordinate on UIView: https://github.com/Glechik/MapCoordinateDrawer

Resources