How to calculate magnetic heading value to get geographical direction i.e., North, North-East, East, East-South, South, South-West, West, West-North?
As magnetic heading returns only value of degree and its required for me to show the geographical direction, on the basis of continuous updated magnetic heading.
How can I make it possible?
A compass needle will always point towards the magnetic north pole. Magnetic north is a datum. As long as we remember this fact and have a way to see where north is, we can determine which direction we must be pointing in relation to this datum. We call this direction our magnetic heading.
True north is a fixed point on the globe. Magnetic north is quite different. Magnetic north is the direction that a compass needle points to as it aligns with the Earth's magnetic field.
Here's how to take a heading: Determine the direction you want to go. Level the compass to let it point north. Keeping the needle pointing north, rotate the compass body until the big “direction of travel” arrow in the middle points toward your destination.
Below is the code that I have used to display continuously updating geographical direction.
CGFloat currentHeading = newHeading.magneticHeading;
NSString *strDirection = [[NSString alloc] init];
if(gradToRotate >23 && gradToRotate <= 67){
strDirection = @"NE";
} else if(gradToRotate >68 && gradToRotate <= 112){
strDirection = @"E";
} else if(gradToRotate >113 && gradToRotate <= 167){
strDirection = @"SE";
} else if(gradToRotate >168 && gradToRotate <= 202){
strDirection = @"S";
} else if(gradToRotate >203 && gradToRotate <= 247){
strDirection = @"SW";
} else if(gradToRotate >248 && gradToRotate <= 293){
strDirection = @"W";
} else if(gradToRotate >294 && gradToRotate <= 337){
strDirection = @"NW";
} else if(gradToRotate >=338 || gradToRotate <= 22){
strDirection = @"N";
}
It is working fine at my end. Masters are welcome to let me know if any modification required.
Try this example offered by Matt Neuburg on Github. https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch22p775heading/ch35p1035heading/ViewController.swift
func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
var h = newHeading.magneticHeading
let h2 = newHeading.trueHeading // will be -1 if we have no location info
print("\(h) \(h2) ")
if h2 >= 0 {
h = h2
}
let cards = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
var dir = "N"
for (ix, card) in cards.enumerate() {
if h < 45.0/2.0 + 45.0*Double(ix) {
dir = card
break
}
}
print(dir)
}
It is perfect!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With