본문 바로가기

[R]HTML5 Geolocation

The HTML Geolocation API is used to locate a user's position.

HTML Geolocation API는 사용자의 위치를 ​​찾는 데 사용됩니다.




Locate the User's Position

사용자의 위치 찾기


The HTML Geolocation API is used to get the geographical position of a user.

HTML Geolocation API는 사용자의 지리적 위치를 가져 오는 데 사용됩니다.

Since this can compromise privacy, the position is not available unless the user approves it.

이는 개인 정보를 침해 할 수 있으므로 사용자가 승인하지 않는 한 해당 위치를 사용할 수 없습니다.


Note: Geolocation is most accurate for devices with GPS, like iPhone.

참고 : Geolocation은 iPhone과 같이 GPS가있는 기기에서 가장 정확합니다.




Browser Support

브라우저 지원


The numbers in the table specify the first browser version that fully supports Geolocation.

표의 숫자는 Geolocation을 완전히 지원하는 첫 번째 브라우저 버전을 지정합니다.


API

Geolocation

5.0 - 49.0

(http)

50.0 (https)

9.0

3.5

5.0

16.0


Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. 

참고 : Chrome 50부터 Geolocation API는 HTTPS와 같은 보안 컨텍스트에서만 작동합니다. 

If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.

사이트가 HTTP와 같이 보안되지 않은 출처에서 호스팅되는 경우 사용자 위치를 가져 오기위한 요청이 더 이상 작동하지 않습니다.




Using HTML Geolocation

HTML Geolocation 사용


The getCurrentPosition() method is used to return the user's position.

이 getCurrentPosition()메서드는 사용자의 위치를 ​​반환하는 데 사용됩니다.

The example below returns the latitude and longitude of the user's position:

아래 예제는 사용자 위치의 위도와 경도를 반환합니다.


Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
}
</script>
cs



Example explained:

예제 설명 :


Check if Geolocation is supported

Geolocation이 지원되는지 확인하십시오.

If supported, run the getCurrentPosition() method. If not, display a message to the user

지원되는 경우 getCurrentPosition () 메소드를 실행하십시오. 그렇지 않은 경우 사용자에게 메시지를 표시합니다.

If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter (showPosition)

getCurrentPosition () 메서드가 성공하면 매개 변수 (showPosition)에 지정된 함수에 좌표 객체를 반환합니다.

The showPosition() function outputs the Latitude and Longitude

showPosition () 함수는 위도와 경도를 출력합니다.

The example above is a very basic Geolocation script, with no error handling.

위의 예제는 오류 처리가없는 매우 기본적인 Geolocation 스크립트입니다.




Handling Errors and Rejections

오류 및 거부 처리


The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:

이 getCurrentPosition()메서드 의 두 번째 매개 변수는 오류를 처리하는 데 사용됩니다. 사용자의 위치를 ​​얻지 못하면 실행할 함수를 지정합니다.


Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function showError(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;
    }
}
cs





Displaying the Result in a Map

결과를지도에 표시


To display the result in a map, you need access to a map service, like Google Maps.

결과를지도에 표시하려면 Google지도와 같은지도 서비스에 액세스해야합니다.

In the example below, the returned latitude and longitude is used to show the location in a Google Map (using a static image):

아래 예제에서 반환 된 위도와 경도는 정적 이미지를 사용하여 Google지도에서 위치를 표시하는 데 사용됩니다.


Example

1
2
3
4
5
6
7
8
function showPosition(position) {
    var latlon = position.coords.latitude + "," + position.coords.longitude;
 
    var 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+"'>";
}
cs



Google Map Script


How to show an interactive Google Map with a marker, zoom and drag options.

마커, 확대 / 축소 및 드래그 옵션을 사용하여 대화식 Google지도를 표시하는 방법.




Location-specific Information

위치 별 정보


This page has demonstrated how to show a user's position on a map.

이 페이지에서는지도에서 사용자의 위치를 ​​표시하는 방법을 보여줍니다.

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

Geolocation은 다음과 같이 위치 별 정보에도 매우 유용합니다.

Up-to-date local information

최신 지역 정보

Showing Points-of-interest near the user

사용자 주변의 관심 지점 표시

Turn-by-turn navigation (GPS)

단계별 네비게이션 (GPS)




The getCurrentPosition() Method - Return Data

getCurrentPosition () 메소드 - 데이터 리턴


The getCurrentPosition() method returns an object on success. 

이 getCurrentPosition()메서드는 성공하면 개체를 반환합니다. 

The latitude, longitude and accuracy properties are always returned. The other properties are returned if available:

위도, 경도 및 정확도 속성은 항상 반환됩니다. 가능한 경우 다른 속성이 반환됩니다.


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)




Geolocation Object - Other interesting Methods

Geolocation 객체 - 기타 흥미로운 메소드


The Geolocation object also has other interesting methods:

Geolocation 객체에는 다른 흥미로운 메소드가 있습니다.

watchPosition() - Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).

watchPosition() - 사용자의 현재 위치를 반환하고 사용자가 이동할 때 업데이트 된 위치를 계속 반환합니다 (예 : 자동차의 GPS).

clearWatch() - Stops the watchPosition() method.

clearWatch()- watchPosition()메소드를 중지합니다 .

The example below shows the watchPosition() method. You need an accurate GPS device to test this (like iPhone):

아래 예는이 watchPosition()방법을 보여줍니다 . 이를 테스트하려면 정확한 GPS 장치가 필요합니다 (예 : iPhone).


Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
}
</script>
cs