กิจกรรม

เลือกแพลตฟอร์ม: Android iOS JavaScript

หน้านี้อธิบายเหตุการณ์อินเทอร์เฟซผู้ใช้และเหตุการณ์ข้อผิดพลาดที่คุณสามารถฟังและจัดการแบบเป็นโปรแกรมได้

เหตุการณ์ในอินเทอร์เฟซผู้ใช้

JavaScript ภายในเบราว์เซอร์เป็นแบบขับเคลื่อนด้วยเหตุการณ์ ซึ่งหมายความว่า JavaScript จะตอบสนองต่อการโต้ตอบโดยการสร้างเหตุการณ์ และคาดหวังให้โปรแกรมรอเหตุการณ์ที่น่าสนใจ เหตุการณ์มี 2 ประเภท ได้แก่

  • ระบบจะเผยแพร่เหตุการณ์ของผู้ใช้ (เช่น เหตุการณ์เมาส์ "คลิก") จาก DOM ไปยัง Maps JavaScript API เหตุการณ์เหล่านี้แยกต่างหากและแตกต่างจากเหตุการณ์ DOM มาตรฐาน
  • การแจ้งเตือนการเปลี่ยนแปลงสถานะ MVC จะแสดงการเปลี่ยนแปลงในออบเจ็กต์ Maps JavaScript API และตั้งชื่อโดยใช้รูปแบบ property_changed

ออบเจ็กต์ Maps JavaScript API แต่ละรายการจะส่งออกเหตุการณ์ที่มีชื่อจำนวนหนึ่ง โปรแกรมที่สนใจเหตุการณ์บางอย่างจะลงทะเบียนListener เหตุการณ์ JavaScript สำหรับเหตุการณ์เหล่านั้น และเรียกใช้โค้ดเมื่อได้รับเหตุการณ์เหล่านั้นโดยเรียกใช้ addListener() เพื่อลงทะเบียนตัวแฮนเดิลเหตุการณ์ในออบเจ็กต์

ตัวอย่างต่อไปนี้แสดงเหตุการณ์ที่ทริกเกอร์โดย google.maps.Map ขณะที่คุณโต้ตอบกับแผนที่

ดูรายการเหตุการณ์ทั้งหมดได้ในเอกสารอ้างอิง Maps JavaScript API เหตุการณ์จะแสดงในส่วนแยกต่างหากสำหรับแต่ละออบเจ็กต์ที่มีเหตุการณ์

เหตุการณ์ UI

ออบเจ็กต์บางรายการภายใน Maps JavaScript API ออกแบบมาเพื่อตอบสนองต่อเหตุการณ์ของผู้ใช้ เช่น เหตุการณ์เมาส์หรือแป้นพิมพ์ ตัวอย่างเช่น เหตุการณ์ของผู้ใช้บางส่วนที่ออบเจ็กต์ google.maps.marker.AdvancedMarkerElement สามารถฟังได้มีดังนี้

  • 'gmp-click'
  • 'gmp-drag'
  • 'gmp-dragstart'
  • 'gmp-dragend'

ดูรายการทั้งหมดได้ที่คลาส AdvancedMarkerElement เหตุการณ์เหล่านี้อาจดูเหมือนเหตุการณ์ DOM มาตรฐาน แต่จริงๆ แล้วเป็นส่วนหนึ่งของ Maps JavaScript API เนื่องจากเบราว์เซอร์ต่างๆ ใช้โมเดลเหตุการณ์ DOM ที่แตกต่างกัน Maps JavaScript API จึงมีกลไกเหล่านี้เพื่อฟังและตอบสนองต่อเหตุการณ์ DOM โดยไม่จำเป็นต้องจัดการกับลักษณะเฉพาะต่างๆ ของเบราว์เซอร์ที่แตกต่างกัน โดยปกติแล้ว เหตุการณ์เหล่านี้จะส่งอาร์กิวเมนต์ภายในเหตุการณ์ที่ระบุสถานะ UI บางอย่าง (เช่น ตำแหน่งเมาส์) ด้วย

การเปลี่ยนแปลงสถานะ MVC

โดยปกติแล้วออบเจ็กต์ MVC จะมีสถานะ เมื่อใดก็ตามที่พร็อพเพอร์ตี้ของออบเจ็กต์มีการเปลี่ยนแปลง Maps JavaScript API จะเริ่มเหตุการณ์ที่พร็อพเพอร์ตี้มีการเปลี่ยนแปลง เช่น API จะเริ่มเหตุการณ์ zoom_changed บนแผนที่เมื่อระดับการซูมของแผนที่เปลี่ยนแปลง คุณยังสกัดกั้นการเปลี่ยนแปลงสถานะเหล่านี้ได้โดยเรียกใช้ addListener() เพื่อลงทะเบียนตัวแฮนเดิลเหตุการณ์ในออบเจ็กต์ด้วย

เหตุการณ์ของผู้ใช้และการเปลี่ยนแปลงสถานะ MVC อาจดูคล้ายกัน แต่คุณควรจัดการเหตุการณ์เหล่านี้แตกต่างกันในโค้ด ตัวอย่างเช่น เหตุการณ์ MVC จะไม่ส่งอาร์กิวเมนต์ภายในเหตุการณ์ ตรวจสอบพร็อพเพอร์ตี้ที่เปลี่ยนแปลงในสถานะ MVC โดยเรียกใช้เมธอด getProperty ที่เหมาะสมในออบเจ็กต์นั้น

จัดการเหตุการณ์

หากต้องการลงทะเบียนรับการแจ้งเตือนเหตุการณ์ ให้ใช้แฮนเดิลเหตุการณ์ addListener() เมธอดดังกล่าวจะรับเหตุการณ์เพื่อรอฟัง และฟังก์ชันที่จะเรียกใช้เมื่อเกิดเหตุการณ์ที่ระบุ

ตัวอย่าง: เหตุการณ์แผนที่และเครื่องหมาย

โค้ดต่อไปนี้จะผสมเหตุการณ์ของผู้ใช้กับเหตุการณ์การเปลี่ยนแปลงสถานะ ตัวอย่างนี้จะแนบตัวแฮนเดิลเหตุการณ์กับเครื่องหมายที่ซูมแผนที่เมื่อคลิก นอกจากนี้ยังแนบเครื่องจัดการเหตุการณ์กับแผนที่สำหรับการเปลี่ยนแปลงพร็อพเพอร์ตี้ center และเลื่อนแผนที่กลับไปยังเครื่องหมายหลังจากผ่านไป 3 วินาทีเมื่อได้รับเหตุการณ์ center_changed

TypeScript

async function init() {
    // Request needed libraries.
    const [{ AdvancedMarkerElement }, { LatLng }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('core'),
        google.maps.importLibrary('maps'),
    ]);

    // Retrieve the map element.
    const mapElement = document.querySelector('gmp-map')!;

    // Get the inner map from the map element.
    const innerMap = mapElement.innerMap;

    const originalPosition = new LatLng(mapElement.center!);

    const marker = new AdvancedMarkerElement({
        position: originalPosition,
        map: innerMap,
        title: 'Click to zoom',
        gmpClickable: true,
    });

    innerMap.addListener('center_changed', () => {
        // 3 seconds after the center of the map has changed,
        // pan back to the marker.
        window.setTimeout(() => {
            innerMap.panTo(originalPosition);
        }, 3000);
    });

    // Zoom in when the marker is clicked.
    marker.addEventListener('gmp-click', () => {
        innerMap.setZoom(8);
        innerMap.setCenter(originalPosition);
    });
}

void init();

JavaScript

async function init() {
    // Request needed libraries.
    const [{ AdvancedMarkerElement }, { LatLng }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('core'),
        google.maps.importLibrary('maps'),
    ]);

    // Retrieve the map element.
    const mapElement = document.querySelector('gmp-map');

    // Get the inner map from the map element.
    const innerMap = mapElement.innerMap;

    const originalPosition = new LatLng(mapElement.center);

    const marker = new AdvancedMarkerElement({
        position: originalPosition,
        map: innerMap,
        title: 'Click to zoom',
        gmpClickable: true,
    });

    innerMap.addListener('center_changed', () => {
        // 3 seconds after the center of the map has changed,
        // pan back to the marker.
        window.setTimeout(() => {
            innerMap.panTo(originalPosition);
        }, 3000);
    });

    // Zoom in when the marker is clicked.
    marker.addEventListener('gmp-click', () => {
        innerMap.setZoom(8);
        innerMap.setCenter(originalPosition);
    });
}

void init();
ดูตัวอย่าง

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

เคล็ดลับ: หากคุณพยายามตรวจหาการเปลี่ยนแปลงในวิวพอร์ต ให้ใช้เหตุการณ์ bounds_changed ที่เฉพาะเจาะจงแทนเหตุการณ์ zoom_changed และ center_changed ที่เป็นองค์ประกอบ เนื่องจาก Maps JavaScript API เริ่มเหตุการณ์หลังๆ เหล่านี้อย่างเป็นอิสระ getBounds() จึงอาจไม่รายงานผลลัพธ์ที่เป็นประโยชน์จนกว่าวิวพอร์ตจะเปลี่ยนแปลงอย่างเป็นทางการ หากต้องการgetBounds()หลังจากเหตุการณ์ดังกล่าว ให้ตรวจสอบเหตุการณ์ bounds_changed แทน

ตัวอย่าง: เหตุการณ์การแก้ไขและการลากรูปร่าง

เมื่อมีการแก้ไขหรือลากรูปร่าง ระบบจะเริ่มเหตุการณ์เมื่อการดำเนินการเสร็จสมบูรณ์ ดูรายการเหตุการณ์และข้อมูลโค้ดบางส่วนได้ที่รูปร่าง

ดูตัวอย่าง (rectangle-event.html)

เข้าถึงอาร์กิวเมนต์ในเหตุการณ์ UI

โดยทั่วไปแล้ว เหตุการณ์ UI ภายใน Maps JavaScript API จะส่งอาร์กิวเมนต์เหตุการณ์ ซึ่ง Listener เหตุการณ์สามารถเข้าถึงได้ โดยจะระบุสถานะ UI เมื่อเกิดเหตุการณ์ขึ้น ตัวอย่างเช่น เหตุการณ์ 'click' ของ UI มักจะส่ง MouseEvent ที่มีพร็อพเพอร์ตี้ latLng ซึ่งแสดงตำแหน่งที่คลิกบนแผนที่ โปรดทราบว่าลักษณะการทำงานนี้มีไว้สำหรับเหตุการณ์ UI เท่านั้น การเปลี่ยนแปลงสถานะ MVC จะไม่ส่งอาร์กิวเมนต์ในเหตุการณ์

คุณสามารถเข้าถึงอาร์กิวเมนต์ของเหตุการณ์ภายใน Listener เหตุการณ์ได้ในลักษณะเดียวกับที่เข้าถึงพร็อพเพอร์ตี้ของออบเจ็กต์ ตัวอย่างต่อไปนี้จะเพิ่ม Listener เหตุการณ์สำหรับแผนที่ และสร้างเครื่องหมายเมื่อผู้ใช้คลิกแผนที่ที่ตำแหน่งที่คลิก

TypeScript

async function init() {
    // Request needed libraries.
    const [{ AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('maps'),
    ]);

    const mapElement = document.querySelector('gmp-map')!;
    const innerMap = mapElement.innerMap;

    innerMap.addListener('click', (event: google.maps.MapMouseEvent) => {
        if (!event.latLng) return;
        new AdvancedMarkerElement({
            position: event.latLng,
            map: innerMap,
        });
        innerMap.panTo(event.latLng);
    });
}

void init();

JavaScript

async function init() {
    // Request needed libraries.
    const [{ AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('maps'),
    ]);

    const mapElement = document.querySelector('gmp-map');
    const innerMap = mapElement.innerMap;

    innerMap.addListener('click', (event) => {
        if (!event.latLng) return;
        new AdvancedMarkerElement({
            position: event.latLng,
            map: innerMap,
        });
        innerMap.panTo(event.latLng);
    });
}

void init();
ดูตัวอย่าง

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

ใช้ Closure ใน Listener เหตุการณ์

เมื่อเรียกใช้ Listener เหตุการณ์ การมีทั้งข้อมูลส่วนตัวและข้อมูลถาวรที่แนบมากับออบเจ็กต์มักจะเป็นประโยชน์ JavaScript ไม่รองรับข้อมูลอินสแตนซ์ "ส่วนตัว" แต่รองรับ Closure ซึ่งช่วยให้ฟังก์ชันภายในเข้าถึงตัวแปรภายนอกได้ Closure มีประโยชน์ภายใน Listener เหตุการณ์เพื่อเข้าถึงตัวแปรที่ไม่ได้แนบมากับออบเจ็กต์ที่เกิดเหตุการณ์ตามปกติ

ตัวอย่างต่อไปนี้ใช้การปิดฟังก์ชันใน Listener เหตุการณ์เพื่อกำหนดข้อความลับให้กับชุดเครื่องหมาย การคลิกเครื่องหมายแต่ละรายการจะแสดงส่วนหนึ่งของข้อความลับซึ่งไม่ได้อยู่ในเครื่องหมายนั้น

TypeScript

async function init() {
    // Request needed libraries.
    const [{ AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('maps'),
    ]);

    const mapElement = document.querySelector('gmp-map')!;
    const innerMap = mapElement.innerMap;

    const bounds: google.maps.LatLngBoundsLiteral = {
        north: -25.363882,
        south: -31.203405,
        east: 131.044922,
        west: 125.244141,
    };

    // Display the area between the location southWest and northEast.
    innerMap.fitBounds(bounds);

    // Add 5 markers to map at random locations.
    // For each of these markers, give them a title with their index, and when
    // they are clicked they should open an infoWindow with text from a secret
    // message.
    const secretMessages = ['This', 'is', 'the', 'secret', 'message'];
    const lngSpan = bounds.east - bounds.west;
    const latSpan = bounds.north - bounds.south;

    for (const secretMessage of secretMessages) {
        const marker = new AdvancedMarkerElement({
            position: {
                lat: bounds.south + latSpan * Math.random(),
                lng: bounds.west + lngSpan * Math.random(),
            },
            map: innerMap,
            gmpClickable: true,
        });

        void attachSecretMessage(marker, secretMessage);
    }
}

// Attaches an info window to a marker with the provided message. When the
// marker is clicked, the info window will open with the secret message.
async function attachSecretMessage(
    marker: google.maps.marker.AdvancedMarkerElement,
    secretMessage: string
) {
    const { InfoWindow } = await google.maps.importLibrary('maps');

    const infoWindow = new InfoWindow({
        content: secretMessage,
    });

    marker.addEventListener('gmp-click', () => {
        infoWindow.open(marker.map, marker);
    });
}

void init();

JavaScript

async function init() {
    // Request needed libraries.
    const [{ AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('maps'),
    ]);

    const mapElement = document.querySelector('gmp-map');
    const innerMap = mapElement.innerMap;

    const bounds = {
        north: -25.363882,
        south: -31.203405,
        east: 131.044922,
        west: 125.244141,
    };

    // Display the area between the location southWest and northEast.
    innerMap.fitBounds(bounds);

    // Add 5 markers to map at random locations.
    // For each of these markers, give them a title with their index, and when
    // they are clicked they should open an infoWindow with text from a secret
    // message.
    const secretMessages = ['This', 'is', 'the', 'secret', 'message'];
    const lngSpan = bounds.east - bounds.west;
    const latSpan = bounds.north - bounds.south;

    for (const secretMessage of secretMessages) {
        const marker = new AdvancedMarkerElement({
            position: {
                lat: bounds.south + latSpan * Math.random(),
                lng: bounds.west + lngSpan * Math.random(),
            },
            map: innerMap,
            gmpClickable: true,
        });

        void attachSecretMessage(marker, secretMessage);
    }
}

// Attaches an info window to a marker with the provided message. When the
// marker is clicked, the info window will open with the secret message.
async function attachSecretMessage(marker, secretMessage) {
    const { InfoWindow } = await google.maps.importLibrary('maps');

    const infoWindow = new InfoWindow({
        content: secretMessage,
    });

    marker.addEventListener('gmp-click', () => {
        infoWindow.open(marker.map, marker);
    });
}

void init();
ดูตัวอย่าง

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

รับและตั้งค่าพร็อพเพอร์ตี้ภายในตัวแฮนเดิลเหตุการณ์

ไม่มีเหตุการณ์การเปลี่ยนแปลงสถานะ MVC ในระบบเหตุการณ์ Maps JavaScript API ที่ส่งอาร์กิวเมนต์เมื่อมีการทริกเกอร์เหตุการณ์ (เหตุการณ์ของผู้ใช้จะส่งอาร์กิวเมนต์ที่ตรวจสอบได้) หากต้องการตรวจสอบพร็อพเพอร์ตี้ในการเปลี่ยนแปลงสถานะ MVC คุณควรเรียกใช้เมธอด getProperty() ที่เหมาะสมในออบเจ็กต์นั้นอย่างชัดเจน การตรวจสอบนี้จะดึงข้อมูลกลับมาเสมอ สถานะปัจจุบัน ของอ็อบเจ็กต์ MVC ซึ่งอาจไม่ใช่สถานะเมื่อเหตุการณ์ถูกเรียกใช้งานครั้งแรก

หมายเหตุ: การตั้งค่าพร็อพเพอร์ตี้อย่างชัดเจนภายในเครื่องจัดการเหตุการณ์ที่ตอบสนองต่อการเปลี่ยนแปลงสถานะของพร็อพเพอร์ตี้นั้นๆ อาจทำให้เกิดลักษณะการทำงานที่คาดเดาไม่ได้และ/หรือไม่พึงประสงค์ ตัวอย่างเช่น การตั้งค่าพร็อพเพอร์ตี้ดังกล่าวจะทริกเกอร์เหตุการณ์ใหม่ และหากคุณตั้งค่าพร็อพเพอร์ตี้ภายในเครื่องจัดการเหตุการณ์นี้เสมอ คุณอาจสร้างลูปที่ไม่มีที่สิ้นสุด

ตัวอย่างด้านล่างแสดงวิธีตั้งค่าตัวแฮนเดิลเหตุการณ์เพื่อตอบสนองต่อเหตุการณ์การซูมโดยแสดงหน้าต่างข้อมูลที่แสดงระดับนั้น

TypeScript

async function init() {
    // Request needed libraries.
    const { InfoWindow } = await google.maps.importLibrary('maps');

    const mapElement = document.querySelector('gmp-map')!;
    const innerMap = mapElement.innerMap;

    const infoWindow = new InfoWindow({
        content: 'Change the zoom level',
        position: mapElement.center,
    });

    infoWindow.open(innerMap);

    innerMap.addListener('zoom_changed', () => {
        infoWindow.setContent('Zoom: ' + innerMap.getZoom()!);
    });
}

void init();

JavaScript

async function init() {
    // Request needed libraries.
    const { InfoWindow } = await google.maps.importLibrary('maps');

    const mapElement = document.querySelector('gmp-map');
    const innerMap = mapElement.innerMap;

    const infoWindow = new InfoWindow({
        content: 'Change the zoom level',
        position: mapElement.center,
    });

    infoWindow.open(innerMap);

    innerMap.addListener('zoom_changed', () => {
        infoWindow.setContent('Zoom: ' + innerMap.getZoom());
    });
}

void init();
ดูตัวอย่าง

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

นำ Listener เหตุการณ์ออก

หากต้องการนำ Listener เหตุการณ์ที่เฉพาะเจาะจงออก คุณต้องกำหนด Listener ดังกล่าวให้กับตัวแปร จากนั้นคุณจะเรียกใช้ removeListener() ได้โดยส่งชื่อตัวแปรที่กำหนดให้กับ Listener

var listener1 = marker.addListener('click', aFunction);

google.maps.event.removeListener(listener1);

หากต้องการนำ Listener ทั้งหมดออกจากอินสแตนซ์หนึ่งๆ ให้เรียกใช้ clearInstanceListeners() โดยส่งชื่ออินสแตนซ์

var listener1 = marker.addListener('click', aFunction);
var listener2 = marker.addListener('mouseover', bFunction);

// Remove listener1 and listener2 from marker instance.
google.maps.event.clearInstanceListeners(marker);

หากต้องการนำ Listener ทั้งหมดสำหรับประเภทเหตุการณ์ที่เฉพาะเจาะจงสำหรับอินสแตนซ์ที่เฉพาะเจาะจงออก ให้เรียกใช้ clearListeners() โดยส่งชื่ออินสแตนซ์และชื่อเหตุการณ์

marker.addListener('click', aFunction);
marker.addListener('click', bFunction);
marker.addListener('click', cFunction);

// Remove all click listeners from marker instance.
google.maps.event.clearListeners(marker, 'click');

ดูข้อมูลเพิ่มเติมได้ในเอกสารอ้างอิงสำหรับเนมสเปซ google.maps.event

คอยฟังข้อผิดพลาดในการตรวจสอบสิทธิ์

หากต้องการตรวจหาความล้มเหลวในการตรวจสอบสิทธิ์แบบเป็นโปรแกรม (เช่น เพื่อส่งบีคอนโดยอัตโนมัติ) คุณสามารถเตรียมฟังก์ชัน Callback ไว้ได้ หากมีการกำหนดฟังก์ชันส่วนกลางต่อไปนี้ ระบบจะเรียกใช้ฟังก์ชันดังกล่าวเมื่อการตรวจสอบสิทธิ์ไม่สำเร็จ function gm_authFailure() { /* Code */ };

ใน TypeScript คุณอาจต้องเพิ่มฟังก์ชันลงในขอบเขตส่วนกลาง ดังที่แสดงด้านล่าง

// Define the callback function.
window.gm_authFailure = () => {
  console.error("Google Maps failed to authenticate.");
  /* Code */
};

// Add gm_authFailure to the global scope.
declare global {
  interface Window {
    gm_authFailure?: () => void;
  }
}
export {};