בדף הזה מתוארים אירועים בממשק המשתמש ואירועי שגיאה שאפשר להאזין להם ולטפל בהם באופן פרוגרמטי.
אירועים בממשק המשתמש
JavaScript בדפדפן מונע על ידי אירועים, כלומר JavaScript מגיב לאינטראקציות על ידי יצירת אירועים, ומצפה שתוכנית תאזין לאירועים מעניינים. יש שני סוגים של אירועים:
- אירועי משתמש (כמו אירועי "קליק" בעכבר) מועברים מה-DOM אל Maps JavaScript API. האירועים האלה נפרדים ושונים מאירועי DOM רגילים.
- התראות על שינוי מצב של MVC משקפות שינויים באובייקטים של Maps JavaScript API, והשמות שלהן נקבעים לפי המוסכמה
property_changed.
כל אובייקט של Maps JavaScript API מייצא מספר אירועים בעלי שם.
תוכנות שמתעניינות באירועים מסוימים ירשמו רכיבי event listener של JavaScript לאירועים האלה, ויריצו קוד כשהאירועים האלה יתקבלו על ידי קריאה ל-addListener() כדי לרשום גורמים מטפלים באירועים באובייקט.
הדוגמה הבאה מראה אילו אירועים מופעלים על ידי google.maps.Map כשיוצרים אינטראקציה עם המפה.
רשימה מלאה של האירועים מופיעה בחומר העזר בנושא Maps JavaScript API. האירועים מפורטים בקטע נפרד לכל אובייקט שמכיל אירועים.
אירועים בממשק המשתמש
חלק מהאובייקטים ב-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 ולהגיב להם בלי צורך לטפל במאפיינים הייחודיים של הדפדפנים השונים. בדרך כלל, האירועים האלה גם מעבירים ארגומנטים בתוך האירוע, שמציינים מצב מסוים של ממשק המשתמש (כמו מיקום העכבר).
שינויים במצב של MVC
אובייקטים של MVC בדרך כלל מכילים מצב. בכל פעם שמאפיין של אובייקט משתנה, Maps JavaScript API מפעיל אירוע שהמאפיין השתנה.
לדוגמה, ה-API יפעיל אירוע zoom_changed במפה כשמשתנה רמת הזום של המפה. אפשר ליירט את השינויים האלה במצב על ידי קריאה ל-addListener() כדי לרשום גורמים מטפלים באירועים גם באובייקט.
אירועי משתמשים ושינויים במצב ה-MVC עשויים להיראות דומים, אבל צריך להתייחס אליהם באופן שונה בקוד. לדוגמה, אירועי MVC לא מעבירים ארגומנטים בתוך האירוע. כדי לבדוק את המאפיין שהשתנה בשינוי מצב של MVC, צריך להפעיל את ה-method המתאים של 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 במקום זאת.
דוגמה: אירועים של עריכת צורות וגרירה
כשעורכים או גוררים צורה, מופעל אירוע בסיום הפעולה. רשימה של האירועים וכמה קטעי קוד מופיעים בקטע צורות.
ארגומנטים של גישה באירועים בממשק המשתמש
אירועים בממשק המשתמש ב-Maps JavaScript API בדרך כלל מעבירים ארגומנט של אירוע, שאליו רכיב ה-event listener יכול לגשת, ומציינים את מצב ממשק המשתמש כשהאירוע התרחש. לדוגמה, אירוע 'click' של ממשק המשתמש בדרך כלל מעביר
MouseEvent שמכיל מאפיין latLng שמציין
את המיקום במפה שעליו לחצו. שימו לב שההתנהגות הזו ייחודית לאירועים בממשק המשתמש. שינויים במצב של MVC לא מעבירים ארגומנטים באירועים שלהם.
אפשר לגשת לארגומנטים של האירוע בתוך רכיב event listener באותו אופן שבו ניגשים למאפיינים של אובייקט. בדוגמה הבאה מוסיפים למפה רכיב event 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();
דוגמה לניסיון
שימוש ב-closures ברכיבי event listener
כשמפעילים רכיב event listener, בדרך כלל כדאי לצרף לאובייקט גם נתונים פרטיים וגם נתונים קבועים. JavaScript לא תומך בנתוני מופעים "פרטיים", אבל הוא תומך בסגירות שמאפשרות לפונקציות פנימיות לגשת למשתנים חיצוניים. סגירות הן שימושיות בתוך רכיבי event listener כדי לגשת למשתנים שבדרך כלל לא מצורפים לאובייקטים שבהם מתרחשים אירועים.
בדוגמה הבאה נעשה שימוש בפונקציית סגירה ברכיב event 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, צריך לקרוא באופן מפורש ל-method המתאים של 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();
דוגמה לניסיון
הסרת רכיבי event listener
כדי להסיר רכיב event listener ספציפי, צריך להקצות אותו למשתנה. אחר כך אפשר להפעיל את removeListener(),
ולהעביר את שם המשתנה שאליו הוקצה המאזין.
var listener1 = marker.addListener('click', aFunction); google.maps.event.removeListener(listener1);
כדי להסיר את כל המאזינים ממופע מסוים, צריך להפעיל את 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);
כדי להסיר את כל המאזינים לסוג אירוע ספציפי במכונה ספציפית, מפעילים את 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.
האזנה לשגיאות אימות
אם אתם רוצים לזהות באופן פרוגרמטי כשל באימות (לדוגמה, כדי לשלוח אות באופן אוטומטי), אתם יכולים להכין פונקציית קריאה חוזרת.
אם הפונקציה הגלובלית הבאה מוגדרת, המערכת תקרא לה כשהאימות ייכשל.
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 {};