-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeolocationAPI.html
62 lines (53 loc) · 2.13 KB
/
geolocationAPI.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE HTML>
<html lang="en">
<head>
<!-- basic.html -->
<title>geolocationAPI</title>
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>The Geolocation API</h1>
<p>
This API is used to access the current position of the user.<br>
It delivers the coordinates as latitude and longitude which can be used in an google maps or openstreetmap URL to
display the position in a visual way. <br>
To use this API you need to call <br>
<code> navigator.geolocation.getCurretnPosition(success, error)</code> <br>
In this example u need to define two functions: <b>success</b> and <b>error</b>. <br>
error is used to display a message like "Unable to retrieve your location" and success is used to deisplay the
accurat position. <br>
As said before, use a function like this: <br>
<code>
function success(position) {<br>
const latitude = position.coords.latitude;<br>
const longitude = position.coords.longitude;<br>
status.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;<br>
}<br>
</code>
To use this correctly you first need to declare a text field with the ID <i>status</i>.<br>
View the source code of this website to see how it is done and try it out below!<br>
</p>
<button id="find-me" onclick="geoFindMe()">Show my location</button><br>
<p id="status"></p>
<script>
function geoFindMe() {
const status = document.querySelector("#status");
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
status.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
}
function error() {
status.textContent = "Unable to retrieve your location due to anything";
}
if (!navigator.geolocation) {
status.textContent = "Geolocation is not supported by your browser";
} else {
status.textContent = "Locating…";
navigator.geolocation.getCurrentPosition(success, error);
}
}
</script>
<a href="index.html"> back </a>
</body>