Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Cách sử dụng HTML5 Geolocation Latitude/Longitude API

HTML5 Geolocation API cho phép trang web lấy vị trí thiết bị (vĩ độ, kinh độ) sau khi user cho phép. Dùng navigator.geolocation.

Ví dụ: Lấy vị trí hiện tại (một lần)

<!DOCTYPE HTML>
<html>
  <head>
    <script type="text/javascript">
      function showLocation(position) {
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        alert("Vĩ độ: " + lat + " Kinh độ: " + lon);
      }
      function errorHandler(err) {
        if (err.code == 1) alert("Lỗi: Truy cập bị từ chối!");
        else if (err.code == 2) alert("Lỗi: Vị trí không xác định!");
      }
      function getLocation() {
        if (navigator.geolocation) {
          var options = {timeout: 60000, enableHighAccuracy: true};
          navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
        } else {
          alert("Trình duyệt không hỗ trợ Geolocation!");
        }
      }
    </script>
  </head>
  <body>
    <form>
      <input type="button" onclick="getLocation();" value="Lấy vị trí"/>
    </form>
  </body>
</html>

Yêu cầu: Trang phải chạy trên HTTPS (hoặc localhost) mới cho phép Geolocation. Luôn xử lý lỗi PERMISSION_DENIED (code 1) và POSITION_UNAVAILABLE (code 2).