Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

Device features

By the end of this chapter, you'll be able to

  • Detect a feature before using it
  • Ask for a permission at the moment it makes sense
  • Compute the distance between two GPS positions
  • React to connection changes

Detect rather than assume

Progressive enhancement means building a base that works everywhere, then adding advanced features only when the device offers them. You test for an API, never for the browser's name:

function features(nav) {
  return {
    location: "geolocation" in nav,
    sharing: typeof nav.share === "function",
    vibration: typeof nav.vibrate === "function",
  };
}

const recentPhone = { geolocation: {}, share() {}, vibrate() {} };
const oldBrowser = { geolocation: {} };
console.log("recent phone:", features(recentPhone));
console.log("old browser:", features(oldBrowser));
recent phone: {"location":true,"sharing":true,"vibration":true}
old browser: {"location":true,"sharing":false,"vibration":false}

In a real page, you pass the browser's navigator object; here, two simulated objects show both cases. On the old browser, the “Share” button is not shown, or offers to copy the link instead.

Ask at the right moment

Sensitive features (location, notifications, camera, microphone) trigger a permission request. A request without context, as soon as the page opens, is almost always refused, and a refusal is hard to recover from: the browser often does not ask again. Good practice: ask when the user takes the action that needs it (they tap “Find the nearest shop”), explaining why.

Refused: the app stays usable, with manual input.

Step 5 of 5
Text description of the animation
  1. The “Near me” button only appears if the feature exists.
  2. The user expresses a need: this is the right moment to ask.
  3. One sentence of explanation before the browser's official request.
  4. Granted: distances are computed, without sending the position to the server if not needed.
  5. Refused: the app stays usable, with manual input.

Computing a distance

A GPS position is a latitude and a longitude, in degrees. For the distance between two points on the Earth's surface, we use the haversine formula, which accounts for the curvature:

function distanceKm([lat1, lon1], [lat2, lon2]) {
  const rad = (d) => (d * Math.PI) / 180;
  const dLat = rad(lat2 - lat1);
  const dLon = rad(lon2 - lon1);
  const a = Math.sin(dLat / 2) ** 2 + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(dLon / 2) ** 2;
  return 2 * 6371 * Math.asin(Math.sqrt(a));
}

const dakar = [14.6928, -17.4467];
const thies = [14.7910, -16.9359];
console.log(`Dakar → Thiès: ${distanceKm(dakar, thies).toFixed(1)} km as the crow flies`);
Dakar → Thiès: 56.0 km as the crow flies

6,371 km is the Earth's mean radius. This is a distance as the crow flies: the road is longer. For distances of a few kilometres, the accuracy of a phone's GPS (often a few metres to a few dozen metres) matters more than the formula's.

Online, offline

navigator.onLine says whether the device thinks it is connected, and the online and offline events report changes. A well-made app shows the state, queues the actions to send, and sends them when the network comes back. Careful: onLine being true only means a network connection exists, not that the Internet answers. Only a real request that succeeds proves it.

Mini-lab: the nearest shopJavaScript

Output

Click “Run” to execute your code.

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: the nearest shop, with a fallback

Write a function nearest(position, shops) that returns the name and distance (rounded to 0.1 km) of the nearest shop. If position is null (permission refused or feature missing), it returns the message “Enter your town to see the shops”.

const shops = { Plateau: [14.6683, -17.4386], Parcelles: [14.7636, -17.4392], Ouakam: [14.7246, -17.4890] };
Hint 1
Compute each shop's distance, then keep the smallest with a loop or reduce.
Hint 2
The null test comes first: it is the fallback.
Show the solution and common mistakes
function distanceKm([lat1, lon1], [lat2, lon2]) {
  const rad = (d) => (d * Math.PI) / 180;
  const a = Math.sin(rad(lat2 - lat1) / 2) ** 2 + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(rad(lon2 - lon1) / 2) ** 2;
  return 2 * 6371 * Math.asin(Math.sqrt(a));
}

const shops = { Plateau: [14.6683, -17.4386], Parcelles: [14.7636, -17.4392], Ouakam: [14.7246, -17.4890] };

function nearest(position, list) {
  if (position === null) return "Enter your town to see the shops";
  let best = null;
  for (const [name, pos] of Object.entries(list)) {
    const d = distanceKm(position, pos);
    if (best === null || d < best.d) best = { name, d };
  }
  return `${best.name}, ${best.d.toFixed(1)} km away`;
}

console.log(nearest([14.7167, -17.4677], shops));
console.log(nearest(null, shops));
Ouakam, 2.5 km away
Enter your town to see the shops

The position does not leave the phone: the computation happens in the page, with the list of shops already downloaded. It is more respectful of privacy, and it even works offline.

Common mistakes:

  • Comparing latitudes and longitudes as distances (Math.abs(lat1 - lat2) + …): one degree of longitude does not represent the same distance depending on the latitude.
  • Forgetting the fallback: without a position, the function crashes on best.name or shows an empty page.

Summary

  1. 1Detect a feature ("geolocation" in navigator) instead of assuming the browser.
  2. 2A permission is requested at the moment of the action that needs it, with an explanation.
  3. 3A refusal must never make the app unusable: plan a fallback.
  4. 4The haversine formula gives the distance as the crow flies between two GPS positions.
  5. 5navigator.onLine and the online/offline events report connectivity, without guaranteeing that the Internet answers.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.