Getting An Arbitrary Type From Reduce - swift

I'm doing a very simple operation. I'm sorting through a bunch of locations in a map to create an enclosing circle, like so:
var maxLong: Double = -180
var maxLat: Double = -180
var minLong: Double = 180
var minLat: Double = 180
for coord in inCoordinates {
maxLong = max(coord.longitude, maxLong)
maxLat = max(coord.latitude, maxLat)
minLong = min(coord.longitude, minLong)
minLat = min(coord.latitude, minLat)
}
let nw: CLLocation = CLLocation(latitude: maxLat, longitude: minLong)
let se: CLLocation = CLLocation(latitude: minLat, longitude: maxLong)
let center = CLLocationCoordinate2D(latitude: (maxLat + minLat) / 2.0, longitude: (maxLong + minLong) / 2.0)
let radiusInMeters = abs(nw.distance(from: se)) / 2.0
return MKCircle(center: center, radius: radiusInMeters)
Pretty straightforward (Yeah, I know about the IDL issue, but I want to keep this simple).
What I'd like to know, is if there were some way I could boil the loop into a variant of reduce, where you would end up with something like this:
let enclosingRect: MKMapRect = inCoordinates.magikalReduce {
// Magic Happens Here -Queue Doug Henning GIF
}
So the returned rect contains the distilled points.
Yeah, I know that I can simply extend Array (with maybe a type qualifier) to do this with a calculated property, but that sort of defeats the purpose of this. The above is fairly efficient, and I'd rather not add overhead, just to be fancy (Which means, even if I could do it, it might be too inefficient to use).
This is more of a curiosity exploration than a technical need. The above code does fine for me, and is relatively zippy.

Do you mean
// calculate the enclosing rect with `reduce` and `union`, you have to create an `MKMapRect` from each coordinate
let enclosingRect = inCoordinates.reduce(MKMapRect.null) { $0.union(MKMapRect(origin: MKMapPoint($1), size: MKMapSize())) }

You can create a struct for holding the min/max longitude and latitude values, then use reduce, where you use the initial values for these for creating an initial result, then creating an updated version of the struct with the necessary min/max calculations.
struct MinMaxCoordinates {
let maxLong:Double
let maxLat:Double
let minLong:Double
let minLat:Double
}
let minMaxCoordinates = inCoordinates.reduce(MinMaxCoordinates(maxLong: -180, maxLat: -180, minLong: 180, minLat: 180), {minMax, coord in
return MinMaxCoordinates(maxLong: max(minMax.maxLong, coord.longitude), maxLat: max(minMax.maxLat, coord.latitude), minLong: min(minMax.minLong, coord.longitude), minLat: max(minMax.minLat, coord.latitude))
})
let nw: CLLocation = CLLocation(latitude: minMaxCoordinates.maxLat, longitude: minMaxCoordinates.minLong)
let se: CLLocation = CLLocation(latitude: minMaxCoordinates.minLat, longitude: minMaxCoordinates.maxLong)
let center = CLLocationCoordinate2D(latitude: (minMaxCoordinates.maxLat + minMaxCoordinates.minLat) / 2.0, longitude: (minMaxCoordinates.maxLong + minMaxCoordinates.minLong) / 2.0)
let radiusInMeters = abs(nw.distance(from: se)) / 2.0
return MKCircle(center: center, radius: radiusInMeters)

Related

can I calculate accurate distance between two latitude and longitude inside a house within 5 meters? [duplicate]

This question already exists:
I want to build something like that if a user enters in a room he recieve a notification in swift ios is it possible?
Closed 3 months ago.
I want to calculate distance between two coordinates within 5 meters or even within one meters is it possible
I have tried haversine formula but not getting the desired result
func calculateDistanceWithHaversin(crrLat: Double, crrLong: Double, desLat: Double = 23.1780068, desLong: Double = 75.7865060, radius: Double = 6367444.7) -> Double {
print("CrrLat \(crrLat) = CrrLong = \(crrLong)")
let haversin = { (angle: Double) -> Double in
return (1 - cos(angle))/2
}
let ahaversin = { (angle: Double) -> Double in
return 2 * asin(sqrt(angle))
}
// degree to radian
let dToR = { (angle: Double) -> Double in
return (angle / 360) * 2 * .pi
}
let lat1 = dToR(crrLat)
let lon1 = dToR(crrLong)
let lat2 = dToR(desLat)
let lon2 = dToR(desLong)
return radius * ahaversin(haversin(lat2 - lat1) + cos(lat1) * cos(lat2) * haversin(lon2 - lon1))
}
i have tried this also
func calculateDistance(crrLat: Double, crrLong: Double) {
let destinationLocation = CLLocation(latitude: 23.1780068, longitude: 75.7865060)
let currentLocation = CLLocation(latitude: crrLat, longitude: crrLong)
distance = currentLocation.distance(from: destinationLocation)
print(String(format: "The distance to my buddy is %.02f m", distance))
}
You can calculate distance with this Builtin Function provided by CoreLocation . The provided distance will be in meters
import CoreLocation
let locationOne = CLLocation(latitude: 37.899, longitude: 74.8989)
let locationTwo = CLLocation(latitude: 38.0900, longitude: 78.98898)
let distance = locationOne.distance(from: locationTwo)

Simplify this foreach loop (to find min/max in a nested array) in swift

I would love to get rid of the foreach loop. Currently I am doing a foreach loop to populate a temp variable to separate my array to get the min/max for each Lat/Lon.
eg: slopeLatLonArray = [ [111,111],[111.1,111.2] ]
func drawFullRouteOverlay() {
/// Reset Array to Nil
vLocations = []
/// populate vLocations as a CLLocation2D
for index in slopeLatLonArray.indices {
vLocations.append(CLLocationCoordinate2D(latitude: Double(slopeLatLonArray[index][0]), longitude: Double(slopeLatLonArray[index][1])))
}
/// Draw the resulting polyline
let polyline = MKPolyline(coordinates: vLocations, count: vLocations.count)
vcTrainMapView.addOverlay(polyline)
/// Bunch of stuffs to do to get the Max/Min of Lat/Lon
var tempLat: [Double] = []
var tempLon: [Double] = []
slopeLatLonArray.forEach {
tempLat.append($0[0])
tempLon.append($0[1])
}
/// Zoom to the entire route polyline
let center = CLLocationCoordinate2D(latitude : (tempLat.min()! + tempLat.max()!) / 2,
longitude: (tempLon.min()! + tempLon.max()!) / 2)
let span = MKCoordinateSpan(latitudeDelta : (tempLat.max()! - tempLat.min()!) * 1.3,
longitudeDelta: (tempLon.max()! - tempLon.min()!) * 1.3)
let region = MKCoordinateRegion(center: center, span: span)
vcTrainMapView.setRegion(region, animated: true)
}
You are unnecessarily iterating all your locations multiple times. First when populating vLocations. Second when populating slopeLatLonArray. Third, fourth, fifth and sixth when getting tempLat and tempLon minimum and maximum values. And another 4 times when getting them again for the span (this might be optimized by the compiler but I am not sure).
What I suggest is to get all those values during the first iteration when populating vLocations. This way you will iterate all locations only once:
func drawFullRouteOverlay() {
guard let first = slopeLatLonArray.first, first.count == 2 else { return }
var minLatitude = first[0]
var maxLatitude = first[0]
var minLongitude = first[1]
var maxLongitude = first[1]
vLocations = slopeLatLonArray.map {
let latitude = $0[0]
let longitude = $0[1]
minLatitude = min(minLatitude, latitude)
maxLatitude = max(maxLatitude, latitude)
minLongitude = min(minLongitude, longitude)
maxLongitude = max(maxLongitude, longitude)
return .init(latitude: latitude, longitude: longitude)
}
/// Draw the resulting polyline
let polyline = MKPolyline(coordinates: vLocations, count: vLocations.count)
vcTrainMapView.addOverlay(polyline)
/// Zoom to the entire route polyline
let center = CLLocationCoordinate2D(latitude: (minLatitude + maxLatitude) / 2, longitude: (minLongitude + maxLongitude) / 2)
let span = MKCoordinateSpan(latitudeDelta: (maxLatitude - minLatitude) * 1.3, longitudeDelta: (maxLongitude - minLongitude) * 1.3)
let region = MKCoordinateRegion(center: center, span: span)
vcTrainMapView.setRegion(region, animated: true)
}
How about either .map...
var tempLat = slopeLatLonArray.map { $0[0] }
var tempLon = slopeLatLonArray.map { $0[1] }
// Could also zip to vLocations for a 1 liner
var vLocations = zip(tempLat, tempLon).map(CLLocationCoordinate2D.init)
or setting in the initial for loop...
var tempLat: [Double] = []
var tempLon: [Double] = []
for index in slopeLatLonArray.indices {
tempLat[index] = Double(slopeLatLonArray[index][0])
tempLon[index] = Double(slopeLatLonArray[index][1])
vLocations.append(CLLocationCoordinate2D(latitude: tempLat[index], longitude: tempLon[index]))
}

Get altitude from a specific given point - mapkit

I am trying to find out altitude from a given point, but I am not getting that with my iPad.
I have defined my altitude var like this:
var altitude: CLLocationDistance = 0.0
I have made this func:
func getAltitude(latitude: CLLocationDistance, longitude: CLLocationDistance) -> CLLocationDistance {
//Get altitude of touched point
locationManager.requestWhenInUseAuthorization()
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
let touchPointLocation = CLLocation(latitude: latitude, longitude: longitude)
let altitude = touchPointLocation.altitude
return altitude
}
For example when I touch the map I tried to get altitude like this, inside the longpress:
let touchPoint = gestureRecognizer.location(in: self.map)
let coord = map.convert(touchPoint, toCoordinateFrom: self.map) //now this coord is working ok. Its touched point coordinates
let altitude = getAltitude(latitude: coord.latitude, longitude: coord.longitude)
print(altitude) //I get 0.0 here :(
Why is this wrong? How can I do this?

How to create an MKCoordinate region similar to 50 miles radius in ios Swift?

I'm trying to create a region similar to a circle radius using CLLocation. I understand radius logic and how its measured in meters, but not so clear on a MKCoordinate region and how long delta and lat delta translate to area. I would like to get a 75 mile region. Here is my code....
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
If you could please provide an explanation more than just a short answer it would be appreciated.
If you're trying to create an actual circular region:
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let radius: CLLocationDistance = 60350.4 // meters for 37.5 miles
let regionIdentifier = "CircularRegion" // any desired String
let circularRegion = CLCircularRegion(center: center, radius: radius, identifier: regionIdentifier)
You could use MKCoordinateRegionMakeWithDistance function:
Creates a new MKCoordinateRegion from the specified coordinate and
distance values.
func MKCoordinateRegionMakeWithDistance(
_ centerCoordinate: CLLocationCoordinate2D,
_ latitudinalMeters: CLLocationDistance,
_ longitudinalMeters: CLLocationDistance) -> MKCoordinateRegion
centerCoordinate - The center point of the new coordinate region.
latitudinalMeters - The amount of north-to-south distance (measured in meters) to use for the span.
longitudinalMeters - The amount of east-to-west distance (measured in meters) to use for the span.
So you will have something like:
let rect = MKCoordinateRegionMakeWithDistance(center, 50 * 1609.34, 50 * 1609.34)

Get all locations within certain radius from SQLite Database in XCode

I have a SQLite Database which contains latitude and longitude of several locations.
I want to find the latitude and longitude of all locations which fall within 15km radius from my current location from my SQLite Database.
What will be my SQLite Query for this?
One degree difference of latitude is equal to 111 km distance, and One degree difference of longitude is equal to 94 km. So Now check for all the latitude which are at (+/-)(15/111) difference and longitudes which are (+/-)(15/94) difference from your current location.
Important link for reference.
For anyone still looking for an answer:
You can get nearby locations with this method adapted from #breceivemail's answer [JAVA]
Here is the translated version in Swift:
private func calculateDerivedPosition(point: CGPoint, range: Double, bearing: Double)-> CGPoint {
let EarthRadius: Double = 6371000
let latA = Double(point.x.degreesToRadians)
let lonA = Double(point.y.degreesToRadians)
let angularDistance = range / EarthRadius
let trueCourse = bearing.degreesToRadians
var lat = asin(sin(latA) * cos(angularDistance) +
cos(latA) * sin(angularDistance) *
cos(trueCourse))
let dlon = atan2(sin(trueCourse) * sin(angularDistance) * cos(latA),
cos(angularDistance) - sin(latA) * sin(lat))
var lon = ((lonA + dlon + Double.pi).truncatingRemainder(dividingBy: (Double.pi * 2))) - Double.pi
lat = lat.radiansToDegrees
lon = lon.radiansToDegrees
let newPoint = CGPoint(x: lat, y: lon)
return newPoint
}
radiansToDegree Extension
And You can use it like this with FMDB (or any Sqlite lib):
let center = CGPoint(x: currentLocation.latitude, y: currentLocation.longitude)
let mult: Double = 1 // mult = 1.1 is more reliable
let radius: Double = 5000 //in meters
let point1 = calculateDerivedPosition(point: center, range: radius * mult, bearing: 0)
let point2 = calculateDerivedPosition(point: center, range: radius * mult, bearing: 90)
let point3 = calculateDerivedPosition(point: center, range: radius * mult, bearing: 180)
let point4 = calculateDerivedPosition(point: center, range: radius * mult, bearing: 270)
let result = try!db.executeQuery("SELECT * FROM items WHERE lat > ? AND lat < ? AND lng < ? AND lng > ?" , values: [point3.x, point1.x, point2.y, point4.y])
Note: The results aren't sorted.
To arrange them in Ascending order, store all the distcnace in a dictionary with key. like,
distanceDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithFloat:distanceVal],#"distance",nil];
[distanceArray addObject:distanceDic];
Here, distanceDic is my Dictionary and distaceVal is string containing distance.
distanceArray is NSMutableArray Containing Distance.
Now Sort the distanceDic like,
NSArray *array = [NSArray arrayWithArray:[distanceArray mutableCopy]]; // Copying NSMutableArray to NSArray.
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"distance" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
array = [array sortedArrayUsingDescriptors:sortDescriptors];
NSLog(#"#The Final Distance Array After Sorting :%#",array);
This will give you resulting Distance Array sorted in Ascending order.