Files
2nd/10_Wiki/Topic_HTML/HTML_Geolocation.md
T
koriweb 9609c04755 docs(10_Wiki): W3Schools 위키화 — HTML/CSS/JavaScript(core)
W3Schools 튜토리얼을 P-Reinforce v3.1 포맷으로 위키화(영어 본문, 한/영 섹션 헤더).
- Topic_HTML: 59문서 (튜토리얼+예제, 레퍼런스/메타 제외)
- Topic_CSS: 190문서 (메인 + Advanced/Flexbox/Grid/RWD 전체)
- Topic_JavaScript: 120문서 (코어 언어; Temporal/DOM상세/BOM/WebAPI/AJAX/jQuery/Graphics 등은 후속)
각 폴더 00_INDEX.md(MOC) 포함. 코드 verbatim, 미확인분은 "Not found in source" 표기.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 19:21:18 +09:00

184 lines
7.6 KiB
Markdown

---
id: html-geolocation
title: "HTML Geolocation"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Geolocation API", "navigator.geolocation", "getCurrentPosition", "watchPosition", "HTML location API"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["html", "web", "frontend", "w3schools", "geolocation", "api", "html5"]
raw_sources: ["https://www.w3schools.com/html/html5_geolocation.asp"]
applied_in: []
github_commit: ""
---
# [[HTML Geolocation]]
## 🎯 한 줄 통찰 (One-line insight)
The HTML Geolocation API locates a user's position (latitude and longitude) via `navigator.geolocation.getCurrentPosition()`, but only with the user's explicit permission and most accurately on GPS-equipped devices. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`navigator.geolocation`** — the entry point to the Geolocation API; check for its existence to detect support. [S1]
- **User permission required** — the API will not return a location until the user grants permission. [S1]
- **`getCurrentPosition(success, error)`** — requests the current position once, calling a success or error callback. [S1]
- **`watchPosition()`** — continuously tracks the position as the user moves. [S1]
- **Accuracy depends on hardware** — works most accurately on devices with GPS (e.g. smartphones, smartwatches). [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Feature-detect first** — `if (navigator.geolocation) { ... } else { /* not supported */ }`. [S1]
- **Two-callback pattern** — pass a success handler that reads `position.coords.*` and an error handler that inspects `error.code`. [S1]
- **Error switch** — branch on `error.code` against `PERMISSION_DENIED`, `POSITION_UNAVAILABLE`, `TIMEOUT`, `UNKNOWN_ERROR`. [S1]
## 📖 세부 내용 (Details)
**Locating the user's position**
The Geolocation API is used to get the geographical position of a user. Because this can compromise privacy, the position is not available unless the user approves it. It is most accurate for devices with GPS, like smartphones. Use the `getCurrentPosition()` method to get the user's position. [S1]
**Basic example**
```javascript
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function success(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function error() {
alert("Sorry, no position available.");
}
</script>
```
The example checks if geolocation is supported, runs `getCurrentPosition()` if so, and on success outputs the latitude and longitude. [S1]
**Handling errors**
The second parameter of `getCurrentPosition()` is used to handle errors. It specifies a function to run if it fails to get the user's location. The error callback can branch on `error.code`: [S1]
```javascript
function error(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
```
**`getCurrentPosition()` return data**
The `getCurrentPosition()` method returns an object on success. The latitude, longitude, and accuracy properties are always returned; the other properties are returned if available. [S1]
| Property | Returns |
|---|---|
| `coords.latitude` | The latitude as a decimal number (always returned) |
| `coords.longitude` | The longitude as a decimal number (always returned) |
| `coords.accuracy` | The accuracy of position (always returned) |
| `coords.altitude` | The altitude in meters above the mean sea level (returned if available) |
| `coords.altitudeAccuracy` | The altitude accuracy of position (returned if available) |
| `coords.heading` | The heading as degrees clockwise from North (returned if available) |
| `coords.speed` | The speed in meters per second (returned if available) |
| `timestamp` | The date/time of the response (returned if available) |
**`watchPosition()`**
The `watchPosition()` method returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car). The matching `clearWatch()` method stops the `watchPosition()` method. [S1]
```javascript
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(success, error);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function success(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function error(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
```
**Secure context note**
The Geolocation API requires a secure context such as HTTPS. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The success/error and watch examples above are the canonical applied cases: a one-shot location lookup and continuous tracking, each with full error handling. A dedicated map-display example and a separate location-specific information sample are described conceptually but not provided as code in the source. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Feature detection + request (JavaScript):
```javascript
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
```
Reading coordinates in the success callback (JavaScript):
```javascript
function success(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. Privacy and security constraints shape usage: a location is never returned without user approval, and the API requires a secure context (HTTPS). [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[HTML Tutorial]]
- **관련 개념:** [[HTML Web APIs]], [[HTML Web Storage]], [[HTML Web Workers]], [[HTML Drag and Drop]]
- **참조 맥락:** Referenced whenever an app needs the user's physical location (maps, local search, geofencing).
## 📚 출처 (Sources)
- [S1] W3Schools — HTML Geolocation — https://www.w3schools.com/html/html5_geolocation.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "HTML Geolocation" page (Astra wiki-curation, P-Reinforce v3.1 format).