Web Geolocation API

Bestemme brugerens position

HTML Geolocation API bruges til at få brugerens geografiske position.

Dette kan potentielt skade privatlivet, og uden brugerens godkendelse er positionen ikke tilgængelig.

Prøv det selv

Bemærk:Geolokalisering er mest præcis for enheder med GPS (f.eks. smartphones).

Alle browsere understøtter Geolocation API:

Chrome IE Firefox Safari Opera
Understøtter Understøtter Understøtter Understøtter Understøtter

Bemærk:Fra Chrome 50 begyndte Geolocation API kun at være tilgængelig i sikre kontekster, f.eks. HTTPS. Hvis din side er hostet på en usikker kilde (f.eks. HTTP), vil anmodningen om at få brugerens position ikke længere fungere.

Brug Geolocation API

getCurrentPosition() Metoden bruges til at returnere brugerens position.

Det følgende eksempel returnerer brugerens bredde- og længdegrader:

Eksempel

<script>
const x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  }
    x.innerHTML = "Geolocation er ikke understøttet af denne browser.";
  }
}
function showPosition(position) {
  x.innerHTML = "Breddegrad: " + position.coords.latitude +
  "Langitude: " + position.coords.longitude;
}
</script>

Prøv det selv

Eksempel forklaring:

  1. Tjek om Geolocation understøttes
  2. Hvis metoden getCurrentPosition() understøttes, skal den køres. Hvis ikke, skal der vises en besked til brugeren
  3. Hvis getCurrentPosition() metoden lykkes, returnerer den en coordinates objekt til den funktion, der er specificeret i parameteren (showPosition)
  4. showPosition() funktionen udskriver bredde- og længdegrader

Det ovenstående eksempel er et meget grundlæggende geolokaliseringsscript uden fejlhåndtering.

Håndtering af fejl og afvisning

getCurrentPosition() Den anden parameter bruges til at håndtere fejl. Hvis det ikke er muligt at få brugerens position, bestemmer den hvilken funktion der skal køres:

Eksempel

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      x.innerHTML = "Brugeren afviste anmodningen om Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML = "Lokaliseringsinformation er ikke tilgængelig."
      break;
    case error.TIMEOUT:
      x.innerHTML = "Anmodningen om at få brugerens position udløb."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML = "En ukendt fejl opstod."
      break;
  }
}

Prøv det selv

Vis resultater på kort

Hvis du vil vise resultater på en kort, skal du besøge korttjenesten, f.eks. Google kort.

In the following example, the returned latitude and longitude are used to display the location on Google Maps (using a static image):

Eksempel

function showPosition(position) {
  let latlon = position.coords.latitude + "," + position.coords.longitude;
  let img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
  "+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";
  document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}

Location-specific information

This page demonstrates how to display the user's location on a map.

Geolocation is also very useful for location-specific information, such as:

  • Latest local information
  • Display points of interest nearby the user
  • Turn-by-turn navigation (GPS)

getCurrentPosition() method - Return data

getCurrentPosition() The method returns an object on success. It will always return latitude, longitude, and accuracy properties. If available, it will return other properties:

Properties Return
coords.latitude Latitude expressed as a decimal number (always returned).
coords.longitude Longitude expressed as a decimal number (always returned).
coords.accuracy Location accuracy (always returned).
coords.altitude Average height above sea level (in meters) (if available).
coords.altitudeAccuracy The height accuracy of the location (if available).
coords.heading Bearing from north clockwise (if available).
coords.speed Speed in meters per second (if available).
timestamp The response date/time (if available).

Geolocation object - Other interesting methods

The Geolocation object also has other interesting methods:

  • watchPosition() - Return the user's current location and continue to return updated locations as the user moves (such as GPS in a car).
  • clearWatch() - Stop the watchPosition () method.

Følgende eksempel viser watchPosition() Metoder. Du har brug for en præcis GPS-enhed til at teste (f.eks. en smartphone):

Eksempel

<script>
const x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(showPosition);
  }
    x.innerHTML = "Geolocation er ikke understøttet af denne browser.";
  }
}
function showPosition(position) {
  x.innerHTML = "Breddegrad: " + position.coords.latitude +
  "Langitude: " + position.coords.longitude;
}
</script>

Prøv det selv