เพิ่ม Google Maps ที่มีเครื่องหมายโดยใช้ JavaScript

บทนำ

บทแนะนำนี้จะแสดงวิธีเพิ่มแผนที่ Google แบบง่ายๆ ด้วยเครื่องหมายลงในเว็บ เหมาะกับผู้ที่มีความรู้เบื้องต้นหรือระดับกลางเกี่ยวกับ HTML และ CSS และความรู้เรื่อง JavaScript เล็กน้อย

ด้านล่างนี้คือแผนที่ที่คุณจะสร้างโดยใช้บทแนะนำนี้ เครื่องหมายอยู่ในตำแหน่ง อูลูรู (หรือที่เรียกว่าเอเยอร์ร็อค) ใน Uluru-Kata Tjuta National Park

เริ่มต้นใช้งาน

การสร้างแผนที่ Google ด้วยเครื่องหมายบนหน้าเว็บของคุณมีสามขั้นตอนดังนี้:

  1. รับคีย์ API
  2. สร้างหน้า HTML
  3. เพิ่มแผนที่โดยใช้เครื่องหมาย

คุณต้องมีเว็บเบราว์เซอร์ เลือกแอปพลิเคชันที่รู้จักกันดี เช่น Google Chrome (แนะนำ), Firefox, Safari หรือ Edge โดยอิงตามแพลตฟอร์มของคุณจาก รายชื่อเบราว์เซอร์ที่รองรับ

ขั้นตอนที่ 1: รับคีย์ API

ส่วนนี้จะอธิบายวิธีตรวจสอบสิทธิ์แอปกับ Maps JavaScript API โดยใช้คีย์ API ของคุณเอง

ทำตามขั้นตอนต่อไปนี้เพื่อรับคีย์ API

  1. ไปที่หน้า Google Cloud Console

  2. สร้างหรือเลือกโปรเจ็กต์

  3. คลิกต่อไปเพื่อเปิดใช้ API และบริการที่เกี่ยวข้อง

  4. ในหน้าข้อมูลเข้าสู่ระบบ ให้รับคีย์ API (และตั้งค่าคีย์ API ข้อจำกัด) หมายเหตุ: หากคุณมีคีย์ API ที่ไม่จำกัดอยู่ หรือคีย์ ด้วยข้อจำกัดของเบราว์เซอร์ คุณสามารถใช้คีย์ดังกล่าวได้

  5. หากต้องการป้องกันการขโมยโควต้าและรักษาความปลอดภัยคีย์ API โปรดดู การใช้คีย์ API

  6. เปิดใช้การเรียกเก็บเงิน โปรดดูการใช้งานและการเรียกเก็บเงิน เพื่อดูข้อมูลเพิ่มเติม

  7. เมื่อคุณมีคีย์ API แล้ว ให้เพิ่มคีย์ลงในข้อมูลโค้ดต่อไปนี้โดยคลิก "YOUR_API_KEY". คัดลอกและวางแท็กสคริปต์ Bootloader เพื่อใช้ของคุณเอง หน้าเว็บ

    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "YOUR_API_KEY",
        v: "weekly",
        // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
        // Add other bootstrap parameters as needed, using camel case.
      });
    </script>
    
    style="height: 400px"

ขั้นตอนที่ 2: สร้างหน้า HTML

นี่คือโค้ดสำหรับหน้าเว็บ HTML พื้นฐาน:

<!doctype html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Add Map</title>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <div id="map"></div>

    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script>
  </body>
</html>

โปรดทราบว่าหน้านี้เป็นหน้าเว็บพื้นฐานมากซึ่งมีส่วนหัวระดับที่ 3 (h3) และ องค์ประกอบเดียวของ div คุณสามารถเพิ่มเนื้อหาใดก็ได้ที่ต้องการลงในหน้าเว็บ

ทำความเข้าใจโค้ด

โค้ดด้านล่างจะสร้างหน้า HTML ที่ประกอบด้วยส่วนหัวและส่วนเนื้อหา

<html>
 <head>
 </head>
 <body>
 </body>
</html>

คุณสามารถเพิ่มส่วนหัวระดับที่ 3 เหนือแผนที่โดยใช้โค้ดด้านล่าง

<h3>My Google Maps Demo</h3>

รหัสด้านล่างนี้จะระบุพื้นที่ของหน้าเว็บสำหรับ Google Maps

<!--The div element for the map -->
<div id="map"></div>

ในขั้นตอนนี้ของบทแนะนำ div จะปรากฏเป็นบล็อกสีเทาเนื่องจาก คุณยังไม่ได้เพิ่มแผนที่ โค้ดด้านล่างอธิบาย CSS ที่ตั้งค่า ขนาดและสีของdiv

/* Set the size of the div element that contains the map */
#map {
    height: 400px; /* The height is 400 pixels */
    width: 100%; /* The width is the width of the web page */
}

ในโค้ดข้างต้น องค์ประกอบ style จะกำหนดขนาด div ของแผนที่ของคุณ ตั้งค่า div ความกว้างและความสูงมากกว่า 0px สำหรับการแสดงแผนที่ ด้วยวิธีนี้ ตัวเรือน div มีความสูง 400 พิกเซล และกว้าง 100% ในการแสดงผล ตามความกว้างของหน้าเว็บ

ตัวโหลด Bootstrap เตรียม Maps JavaScript API สำหรับการโหลด (ไม่มีการโหลดไลบรารีจนกว่าจะมีการเรียกใช้ importLibrary())

<script>
  (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
    key: "YOUR_API_KEY",
    v: "weekly",
    // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
    // Add other bootstrap parameters as needed, using camel case.
  });
</script>

โปรดดูขั้นตอนที่ 3: รับคีย์ API เพื่อดูวิธีการรับคีย์ API คีย์ API ของตัวเอง

ขั้นตอนที่ 3: เพิ่มแผนที่โดยใช้เครื่องหมาย

ส่วนนี้จะแสดงวิธีโหลด Maps JavaScript API ลงใน หน้าเว็บ และวิธีเขียน JavaScript ของคุณเองที่ใช้ API เพื่อเพิ่มแผนที่ พร้อมกับมีเครื่องหมายบนนั้น

TypeScript

// Initialize and add the map
let map;
async function initMap(): Promise<void> {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };

  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

  // The map, centered at Uluru
  map = new Map(
    document.getElementById('map') as HTMLElement,
    {
      zoom: 4,
      center: position,
      mapId: 'DEMO_MAP_ID',
    }
  );

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerElement({
    map: map,
    position: position,
    title: 'Uluru'
  });
}

initMap();

JavaScript

// Initialize and add the map
let map;

async function initMap() {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };
  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

  // The map, centered at Uluru
  map = new Map(document.getElementById("map"), {
    zoom: 4,
    center: position,
    mapId: "DEMO_MAP_ID",
  });

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerElement({
    map: map,
    position: position,
    title: "Uluru",
  });
}

initMap();

ในโค้ดข้างต้น ไลบรารี Map และ AdvancedMarkerView จะโหลดเมื่อ จะมีการเรียกฟังก์ชัน initMap()

ทำความเข้าใจโค้ด

โค้ดด้านล่างจะสร้างอ็อบเจ็กต์ Google Maps ใหม่ และเพิ่มคุณสมบัติลงใน รวมทั้งตำแหน่งศูนย์กลางและระดับการซูม ดูเอกสารเกี่ยวกับ พร็อพเพอร์ตี้อื่นๆ ตัวเลือกเพิ่มเติม

TypeScript

// The location of Uluru
const position = { lat: -25.344, lng: 131.031 };

// Request needed libraries.
//@ts-ignore
const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

// The map, centered at Uluru
map = new Map(
  document.getElementById('map') as HTMLElement,
  {
    zoom: 4,
    center: position,
    mapId: 'DEMO_MAP_ID',
  }
);

JavaScript

// The location of Uluru
const position = { lat: -25.344, lng: 131.031 };
// Request needed libraries.
//@ts-ignore
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

// The map, centered at Uluru
map = new Map(document.getElementById("map"), {
  zoom: 4,
  center: position,
  mapId: "DEMO_MAP_ID",
});

ในโค้ดข้างต้น new Map() จะสร้างวัตถุใหม่ใน Google Maps พร็อพเพอร์ตี้ center จะบอก API ว่าต้องตั้งศูนย์กลางของแผนที่ไว้ที่ใด

เรียนรู้เพิ่มเติมเกี่ยวกับการรับพิกัดละติจูด/ลองจิจูด หรือแปลงที่อยู่ให้เป็นพิกัดทางภูมิศาสตร์

พร็อพเพอร์ตี้ zoom ระบุระดับการซูมสำหรับแผนที่ ซูม: 0 คือต่ำสุด ซูม และแสดงทั้งโลก ตั้งค่าการซูมให้สูงขึ้นเพื่อซูมเข้า Earth ที่มีความละเอียดสูงกว่า

โค้ดด้านล่างวางเครื่องหมายบนแผนที่ พร็อพเพอร์ตี้ position จะตั้งค่า ของเครื่องหมาย

TypeScript

// The marker, positioned at Uluru
const marker = new AdvancedMarkerElement({
  map: map,
  position: position,
  title: 'Uluru'
});

JavaScript

// The marker, positioned at Uluru
const marker = new AdvancedMarkerElement({
  map: map,
  position: position,
  title: "Uluru",
});

ใส่โค้ดตัวอย่างให้ครบถ้วน

ดูตัวอย่างโค้ดทั้งหมดได้ที่

TypeScript

// Initialize and add the map
let map;
async function initMap(): Promise<void> {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };

  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

  // The map, centered at Uluru
  map = new Map(
    document.getElementById('map') as HTMLElement,
    {
      zoom: 4,
      center: position,
      mapId: 'DEMO_MAP_ID',
    }
  );

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerElement({
    map: map,
    position: position,
    title: 'Uluru'
  });
}

initMap();

JavaScript

// Initialize and add the map
let map;

async function initMap() {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };
  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

  // The map, centered at Uluru
  map = new Map(document.getElementById("map"), {
    zoom: 4,
    center: position,
    mapId: "DEMO_MAP_ID",
  });

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerElement({
    map: map,
    position: position,
    title: "Uluru",
  });
}

initMap();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

HTML

<html>
  <head>
    <title>Add Map</title>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <div id="map"></div>

    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script>
  </body>
</html>

ลองใช้ตัวอย่าง

ดูข้อมูลเพิ่มเติมเกี่ยวกับเครื่องหมาย

เคล็ดลับและการแก้ปัญหา

  • คุณสามารถปรับแต่งตัวเลือกต่างๆ เช่น รูปแบบและคุณสมบัติ เพื่อปรับแต่งแผนที่ สำหรับ ข้อมูลเพิ่มเติมเกี่ยวกับการปรับแต่งแผนที่ อ่านคู่มือเพื่อ การจัดรูปแบบ และ การวาดภาพบนแผนที่
  • ใช้คอนโซลเครื่องมือสำหรับนักพัฒนาซอฟต์แวร์ในเว็บเบราว์เซอร์เพื่อทดสอบและเรียกใช้ อ่านรายงานข้อผิดพลาด และแก้ปัญหาเกี่ยวกับโค้ดของคุณได้
  • ใช้แป้นพิมพ์ลัดต่อไปนี้เพื่อเปิดคอนโซลใน Chrome
    Command+Option+J (ใน Mac) หรือ Control+Shift+J (ใน Windows)
  • ทำตามขั้นตอนด้านล่างเพื่อดูละติจูดและ พิกัดลองจิจูดสำหรับตำแหน่งบน Google Maps

    1. เปิด Google Maps ในเบราว์เซอร์
    2. คลิกขวาตรงตำแหน่งบนแผนที่ที่คุณต้องการ พิกัด
    3. เลือกที่นี่คือที่ไหนจากเมนูตามบริบทที่ปรากฏขึ้น แผนที่จะแสดงการ์ดที่ด้านล่างของหน้าจอ ค้นหาละติจูด และพิกัดลองจิจูดในแถวสุดท้ายของการ์ด
  • คุณสามารถแปลงที่อยู่เป็นพิกัดละติจูดและลองจิจูดโดยใช้ บริการเข้ารหัสพิกัดภูมิศาสตร์ คู่มือนักพัฒนาซอฟต์แวร์มีข้อมูลโดยละเอียดเกี่ยวกับ การเริ่มต้นใช้งานบริการ Geocoding