Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

วิธาแสดงตำแหน่งปัจจุบันด้วย HTML5 Geolocation และ Google Maps


บทนำ

รวม Geolocation API กับ Google Maps Static API เพื่อแสดงแผนที่ตำแหน่งปัจจุบัน ต้องมี API Key จาก Google Cloud Console

ขั้นตอนเตรียม API Key

  1. ไปที่ Google Cloud Console
  2. สร้าง Project / เลือก Project
  3. Enable Maps Static API
  4. สร้าง Credentials → API Key
  5. (แนะนำ) จำกัด API Key: HTTP Referrers, IP Addresses

ตัวอย่างโค้ด

<!DOCTYPE HTML>
<html>
  <head>
    <script>
      function showLocation(position) {
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        var latlng = lat + "," + lon;
        var apiKey = "YOUR_API_KEY_HERE"; // ใส่ API Key ของคุณ
        var imgUrl = "https://maps.googleapis.com/maps/api/staticmap?center=" 
          + latlng + "&zoom=14&size=400x300&key=" + apiKey;
        document.getElementById("mapholder").innerHTML = 
          '<img src="' + imgUrl + '" alt="Current Location">';
      }
      function errorHandler(err) {
        if (err.code == 1) alert("Error: Access denied!");
        else if (err.code == 2) alert("Error: Position unavailable!");
      }
      function getLocation() {
        if (navigator.geolocation) {
          var options = {timeout: 60000, enableHighAccuracy: true};
          navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
        } else {
          alert("Browser ไม่รองรับ Geolocation!");
        }
      }
    </script>
  </head>
  <body>
    <div id="mapholder"></div>
    <form>
      <input type="button" onclick="getLocation();" value="Get Location" />
    </form>
  </body>
</html>

Static Map Parameters

Parameterคำอธิบาย
centerLat,Lng หรือ Place Name
zoom0-21 (14 = ระดับเมือง)
sizeWidthxHeight (Max 640x640 Free)
maptyperoadmap, satellite, hybrid, terrain
markersเพิ่ม Marker (color, label, size)
keyAPI Key (จำเป็น)

ตัวอย่างเพิ่ม Marker

var imgUrl = "https://maps.googleapis.com/maps/api/staticmap?"
  + "center=" + latlng
  + "&zoom=15"
  + "&size=400x300"
  + "&markers=color:red%7Clabel:U%7C" + latlng
  + "&key=" + apiKey;

ข้อจำกัด Free Tier

  • 28,000 Requests/เดือน (Static Maps)
  • Max Size 640x640
  • ต้องมี Billing Account แม้ Free Tier

ทางเลือก: Leaflet + OpenStreetMap (Free, No API Key)

<div id="map" style="height: 300px;"></div>
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css">
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<script>
  navigator.geolocation.getCurrentPosition(function(pos) {
    var map = L.map('map').setView([pos.coords.latitude, pos.coords.longitude], 13);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
    L.marker([pos.coords.latitude, pos.coords.longitude]).addTo(map)
      .bindPopup('You are here').openPopup();
  });
</script>