เพิ่ม 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>
    

ขั้นตอนที่ 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 คุณสามารถเพิ่มเนื้อหาใดก็ได้ที่ต้องการลงในหน้าเว็บ

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

ในขณะนี้ ตัวอย่างได้แก่

  • ประกาศแอปพลิเคชันเป็น HTML5 โดยใช้การประกาศ !DOCTYPE html
  • สร้างองค์ประกอบ div ชื่อ "map" แล้ว เพื่อถือแผนที่
  • โหลด Maps JavaScript API โดยใช้ตัวโหลด Bootstrap

ประกาศแอปพลิเคชันของคุณเป็น HTML5

เราขอแนะนำให้คุณประกาศ DOCTYPE จริงในเว็บแอปพลิเคชัน ในตัวอย่างในที่นี้ เราได้ประกาศว่าแอปพลิเคชันของเราเป็น HTML5 โดยใช้แท็ก HTML5 อย่างง่าย DOCTYPE ดังที่แสดงด้านล่าง

<!DOCTYPE html>

เบราว์เซอร์ปัจจุบันส่วนใหญ่จะแสดงเนื้อหาที่ประกาศด้วย DOCTYPE นี้ ใน "โหมดมาตรฐาน" ซึ่งหมายความว่าแอปพลิเคชันของคุณควร ข้ามเบราว์เซอร์ได้ DOCTYPE ยังออกแบบมาให้มีประสิทธิภาพลดลงด้วย เบราว์เซอร์ที่ไม่เข้าใจ โปรแกรมดังกล่าวจะไม่สนใจเบราว์เซอร์ดังกล่าว และใช้ "โหมดที่ไม่มาตรฐาน" ถึง แสดงเนื้อหาของตน

โปรดทราบว่า CSS บางรายการที่ทำงานในโหมดที่ไม่มาตรฐานไม่ถูกต้องใน โหมดมาตรฐาน ในกรณีเฉพาะเจาะจง ขนาดทั้งหมดแบบเปอร์เซ็นต์จะต้องรับค่าเดิมมา จากองค์ประกอบระดับบนสุด และหากมีระดับบนเหล่านั้นล้มเหลว ระบุขนาด โดยให้มีขนาดที่ 0 x 0 พิกเซล สำหรับ เราจึงใส่การประกาศ style ต่อไปนี้ไว้ด้วย

<style>
  #map {
    height: 100%;
  }
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
</style>

สร้างเอลิเมนต์ div

เพื่อให้แผนที่แสดงบนหน้าเว็บ เราต้องจองพื้นที่สำหรับแผนที่นั้น โดยทั่วไป เราดำเนินการดังกล่าวโดยการสร้างเอลิเมนต์ div ที่มีชื่อและรับการอ้างอิงถึง ใน Document Object Model (DOM) ของเบราว์เซอร์

รหัสด้านล่างนี้จะระบุพื้นที่ของหน้าเว็บสำหรับ 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% ในการแสดงผล ตามความกว้างของหน้าเว็บ โปรดทราบว่า div มักจะใช้ความกว้าง จากองค์ประกอบที่มีไว้ และ div ที่ว่างเปล่ามักจะมีความสูง 0 สำหรับกรณีนี้ คุณต้องตั้งค่าความสูงใน div อย่างชัดเจนเสมอ

โหลด Maps JavaScript API

ตัวโหลด 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()

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

ในขั้นตอนนี้ในบทแนะนำ เราจะมีสิ่งต่อไปนี้

  • กำหนดฟังก์ชัน JavaScript ที่สร้างแผนที่ใน div
  • สร้าง AdvancedMarkerElement เพื่อเพิ่มเครื่องหมายลงในแผนที่

เพิ่มแผนที่

โค้ดด้านล่างนี้จะสร้างอ็อบเจ็กต์ 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",
});

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

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

การเสนอแผนที่ของโลกทั้งใบเป็นภาพเดียวจำเป็นต้องมี แผนที่ขนาดมหึมา หรือแผนที่ขนาดเล็กที่มีความละเอียดต่ำมาก ด้วยเหตุนี้ รูปภาพแผนที่ ภายใน Google Maps และ Maps JavaScript API ถูกแบ่งออกเป็น "ชิ้นส่วน" แผนที่ และ "ระดับการซูม" ในระดับการซูมต่ำ ชิ้นส่วนแผนที่ชุดเล็กๆ จะครอบคลุมบริเวณ พื้นที่ ในระดับการซูมที่สูงขึ้น ชิ้นส่วนจะมีความละเอียดสูงขึ้นและครอบคลุม พื้นที่ที่เล็กลง รายการต่อไปนี้จะแสดงระดับรายละเอียดโดยประมาณที่คุณสามารถ คาดว่าจะเห็นเมื่อซูมแต่ละระดับ

  • 1: โลก
  • 5: ผืนดินหรือทวีป
  • 10: เมือง
  • 15: ถนน
  • 20: อาคาร

ภาพ 3 ภาพต่อไปนี้แสดงในตำแหน่งเดียวกันของโตเกียวที่ระดับการซูม 0 7 และ 18

เพิ่มเครื่องหมาย

โค้ดด้านล่างวางเครื่องหมายบนแผนที่ พร็อพเพอร์ตี้ 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