8
- (float)angleFromCoordinate:(CLLocationCoordinate2D)first toCoordinate:(CLLocationCoordinate2D)second {
//first is origin
//second is point
float longitudinalDifference = second.longitude - first.longitude;
float latitudinalDifference = second.latitude - first.latitude;
float possibleAzimuth = (M_PI * .5f) - atan(latitudinalDifference / longitudinalDifference);
if (longitudinalDifference > 0)
{
return possibleAzimuth;
}
else if (longitudinalDifference < 0)
{
return possibleAzimuth + M_PI;
}
else if (latitudinalDifference < 0)
{
return M_PI;
}
return 0.0f;
}
The code above (taken from the open source ARkit project) calculates an angle from a point of interest to a point of origin (the user location). Given the azimuth (heading) calculated in radians, in the AR app im building I can detect whether a point is within its view port using the following code:
- (BOOL)viewportContainsCoordinate:(ARCoordinate *)coordinate {
double centerAzimuth = self.centerCoordinate.azimuth;
double leftAzimuth = centerAzimuth - VIEWPORT_WIDTH_RADIANS / 2.0;
if (leftAzimuth < 0.0) {
leftAzimuth = 2 * M_PI + leftAzimuth;
}
double rightAzimuth = centerAzimuth + VIEWPORT_WIDTH_RADIANS / 2.0;
if (rightAzimuth > 2 * M_PI) {
rightAzimuth = rightAzimuth - 2 * M_PI;
}
BOOL result = (coordinate.azimuth > leftAzimuth && coordinate.azimuth < rightAzimuth); //THIS LINE
if(leftAzimuth > rightAzimuth) {
result = (coordinate.azimuth < rightAzimuth || coordinate.azimuth > leftAzimuth);
}
double centerInclination = self.centerCoordinate.inclination;
double bottomInclination = centerInclination - VIEWPORT_HEIGHT_RADIANS / 2.0;
double topInclination = centerInclination + VIEWPORT_HEIGHT_RADIANS / 2.0;
//check the height.
result = result && (coordinate.inclination > bottomInclination && coordinate.inclination < topInclination);
//NSLog(@"coordinate: %@ re