I run Yaad-e-Namaz, a free prayer times site with no ads. The page people use the most by far is the Qibla finder, which shows Muslims the direction of the Kaaba in Makkah. I wanted it to work straight in the phone browser, without asking anyone to install an app. Here's how it works and what tripped me up.
1. The math: great-circle bearing
The Qibla isn't "the direction on a flat map". It's the start of the shortest path over the globe to the Kaaba (21.4225° N, 39.8262° E). That's a standard initial bearing calculation:
const KAABA = { lat: 21.4225, lng: 39.8262 };
const rad = d => d * Math.PI / 180;
const deg = r => r * 180 / Math.PI;
function qiblaBearing(lat, lng) {
const φ1 = rad(lat), φ2 = rad(KAABA.lat);
const Δλ = rad(KAABA.lng - lng);
const y = Math.sin(Δλ) * Math.cos(φ2);
const x = Math.cos(φ1) * Math.sin(φ2) -
Math.sin(φ1) * Math.cos(φ2) * Math.cos(Δλ);
return (deg(Math.atan2(y, x)) + 360) % 360; // degrees from true north
}
This is why the answer surprises people. From New York the Qibla is about 58° (north-east), not south-east, because the shortest route curves up over the North Atlantic.
2. Reading the phone's heading
The browser gives you orientation through DeviceOrientationEvent, but every platform does it a little differently:
-
iPhone (Safari): you must call
DeviceOrientationEvent.requestPermission()from a button tap, then readevent.webkitCompassHeading. -
Android (Chrome): listen to
deviceorientationabsoluteand use360 - event.alpha.
The arrow on screen is then just qiblaBearing - heading.
3. Magnetic north vs true north
Phone compasses measure magnetic north, but the bearing above is from true north. The gap (magnetic declination) is only a few degrees in Pakistan but can be much more in other places, so the page corrects for it.
4. The real problem: compasses lie indoors
Most complaints I got were "the Qibla keeps changing". That's almost never the code. Phone magnetometers get thrown off by metal, speakers, laptops and magnetic cases. What helped:
- Showing a "move your phone in a figure-8" calibration hint
- Smoothing the heading so the arrow doesn't jitter
- Adding a fixed fallback: a page for every city with the exact angle and distance, e.g. Qibla in Lahore (260°) or Qibla in London (119°). People can line that up with a landmark once and stop relying on the sensor.
Those city pages turned out to be great for SEO too, since people search "qibla direction + city" a lot.
Try it
Open yaadenamaz.com/qibla on your phone and tap the button. I'd love feedback, especially on sensor accuracy across different Android phones.
The same site also has prayer times, the Quran with Urdu and English, hadith and a free prayer times widget you can embed on your own site.
Top comments (0)