TypeScript และ Google Maps

TypeScript เป็นซูเปอร์เซ็ตที่พิมพ์ของ JavaScript ที่คอมไพล์เป็น JavaScript ธรรมดา โค้ดตัวอย่างด้านล่างแสดงการใช้งาน Google Maps อย่างง่ายโดยใช้ TypeScript

TypeScript

async function init(): Promise<void> {
    // Import the needed libraries.
    await google.maps.importLibrary('maps');

    // Access the map.
    const mapElement = document.querySelector('gmp-map')!;
    // Access the underlying map object.
    const innerMap = mapElement.innerMap;

    console.log({ mapElement, innerMap });
}

void init();

JavaScript

async function init() {
    // Import the needed libraries.
    await google.maps.importLibrary('maps');

    // Access the map.
    const mapElement = document.querySelector('gmp-map');
    // Access the underlying map object.
    const innerMap = mapElement.innerMap;

    console.log({ mapElement, innerMap });
}

void init();

CSS

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

HTML

<html>
    <head>
        <title>Simple Map</title>

        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script type="module" src="./index.js"></script>
        <script>
            // prettier-ignore
            (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: "GOOGLE_MAPS_API_KEY"
            });
        </script>
    </head>

    <body>
        <gmp-map center="-34.397,150.644" zoom="8" map-id="DEMO_MAP_ID">
        </gmp-map>
    </body>
</html>
ดูตัวอย่าง

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

โปรเจ็กต์ DefinitelyTyped เป็นโปรเจ็กต์โอเพนซอร์สที่ดูแลรักษาไฟล์การประกาศประเภทสำหรับแพ็กเกจจำนวนมาก รวมถึง Google Maps ใช้ NPM เพื่อติดตั้งไฟล์ประกาศ JavaScript ของ Google Maps จากแพ็กเกจ @types/google.maps

npm i -D @types/google.maps

ดูข้อมูลเพิ่มเติมได้ที่ไฟล์ต้นฉบับใน GitHub

เพิ่ม google.maps ลงในตัวเลือก tsconfig types

หากไฟล์ tsconfig ตั้งค่าตัวเลือกคอมไพเลอร์ types ไว้ TypeScript จะรวมเฉพาะแพ็กเกจ @types ที่แสดงในอาร์เรย์นั้น การติดตั้ง @types/google.maps ไม่เพียงพอที่จะเปิดใช้การรองรับ TypeScript สำหรับ Google Maps และโค้ดที่ใช้เนมสเปซ google จะคอมไพล์ไม่สำเร็จพร้อมข้อผิดพลาดต่อไปนี้

Error T2503: Cannot find namespace 'google'.

วิธีเพิ่ม google.maps ลงในอาร์เรย์ types

{
  "compilerOptions": {
    "types": ["google.maps"]
  }
}

หรือเพิ่มคำสั่งต่อไปนี้ลงในไฟล์ประกาศที่โปรเจ็กต์ของคุณมี เช่น vite-env.d.ts

/// <reference types="google.maps" />

ดูข้อมูลเพิ่มเติมได้ที่ประเภท

แพ็กเกจ @types ที่ขัดแย้งกัน

ไลบรารีบางรายการอาจใช้แพ็กเกจอื่นที่ไม่ใช่ @types/google.maps ซึ่งอาจทำให้เกิดความขัดแย้ง ใช้ตัวเลือกคอมไพเลอร์ skipLibCheck เพื่อหลีกเลี่ยงปัญหาเกี่ยวกับประเภทที่ไม่สอดคล้องกัน

{
  "compilerOptions": {
    "skipLibCheck": true
  }
}

ระบุ typeRoots

เฟรมเวิร์กบางอย่าง เช่น Angular อาจต้องระบุตัวเลือกคอมไพเลอร์ typeRoots เพื่อรวมประเภทที่ติดตั้งจาก @types/google.maps และแพ็กเกจ @types อื่นๆ ทั้งหมด

โดยค่าเริ่มต้น ระบบจะรวมแพ็กเกจ @types ที่มองเห็นได้ทั้งหมดไว้ในการคอมไพล์ ระบบจะถือว่าแพ็กเกจใน node_modules/@types ของโฟลเดอร์ที่ล้อมรอบใดๆ สามารถมองเห็นได้

{
  "compilerOptions": {
    "typeRoots": [
      "node_modules/@types"
    ]
  }
}