אפשר להוסיף למפה צורות שונות. צורה היא אובייקט במפה, שמקושר לקואורדינטות של קו רוחב וקו אורך. אפשר להשתמש בצורות הבאות: קווים, מצולעים, עיגולים ומלבנים. אפשר גם להגדיר את הצורות כך שהמשתמשים יוכלו לערוך או לגרור אותן.
קווים פוליגוניים
כדי לשרטט קו במפה, משתמשים בקו פוליגוני. המחלקות
Polyline מגדירות שכבת-על לינארית של מקטעי קו מחוברים במפה. אובייקט Polyline מורכב ממערך של מיקומי LatLng, ויוצר סדרה של קטעי קו שמחברים את המיקומים האלה ברצף מסודר.
הוספת קו מרובה
הפונקציה Polyline constructor מקבלת קבוצה של
PolylineOptions שמציינת את LatLng
הקואורדינטות של הקו וקבוצה של סגנונות להתאמת ההתנהגות החזותית של הקו.
אובייקטים של Polyline מצוירים כסדרה של קטעים ישרים במפה. אפשר לציין צבעים, עוביים ורמות שקיפות מותאמים אישית לקו המתאר של הקו בתוך התג PolylineOptions כשיוצרים את הקו, או לשנות את המאפיינים האלה אחרי היצירה.
קו פוליגוני תומך בסגנונות הקו הבאים:
-
strokeColorמציין צבע הקסדצימלי ב-HTML בפורמט"#FFFFFF". המחלקותPolylineלא תומכות בצבעים עם שם. - הערך
strokeOpacityמציין ערך מספרי בין0.0ל-1.0כדי לקבוע את אטימות הצבע של הקו. ערך ברירת המחדל הוא1.0. -
strokeWeightמציין את רוחב הקו בפיקסלים.
המאפיין editable של הקו המקומקע קובע אם המשתמשים יכולים לערוך את הצורה. מידע נוסף מופיע בקטע צורות שניתנות לעריכה על ידי המשתמש שבהמשך. באופן דומה, אתם יכולים להגדיר את המאפיין draggable כדי לאפשר למשתמשים לגרור את הקו.
בדוגמה הזו נוצר קו פוליגוני אדום ברוחב שני פיקסלים שמציג את הנתיב של הטיסה הראשונה מעל האוקיינוס השקט בין אוקלנד שבקליפורניה לבין בריסביין שבאוסטרליה.
TypeScript
// This example creates a 2-pixel-wide red polyline showing the path of // the first trans-Pacific flight between Oakland, CA, and Brisbane, // Australia which was made by Charles Kingsford Smith. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 3, center: { lat: 0, lng: -180 }, mapTypeId: "terrain", } ); const flightPlanCoordinates = [ { lat: 37.772, lng: -122.214 }, { lat: 21.291, lng: -157.821 }, { lat: -18.142, lng: 178.431 }, { lat: -27.467, lng: 153.027 }, ]; const flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2, }); flightPath.setMap(map); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a 2-pixel-wide red polyline showing the path of // the first trans-Pacific flight between Oakland, CA, and Brisbane, // Australia which was made by Charles Kingsford Smith. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 3, center: { lat: 0, lng: -180 }, mapTypeId: "terrain", }); const flightPlanCoordinates = [ { lat: 37.772, lng: -122.214 }, { lat: 21.291, lng: -157.821 }, { lat: -18.142, lng: 178.431 }, { lat: -27.467, lng: 153.027 }, ]; const flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2, }); flightPath.setMap(map); } window.initMap = initMap;
דוגמה לניסיון
הסרת קו פוליגוני
כדי להסיר קו רציף מהמפה, קוראים לשיטה setMap() ומעבירים את null כארגומנט. בדוגמה הבאה, flightPath הוא אובייקט של קו רציף:
flightPath.setMap(null);
שימו לב: השיטה שלמעלה לא מוחקת את הקו הפוליגוני. הפעולה הזו מסירה את הקו המישורי מהמפה. אם רוצים למחוק את הקו המרוסק, צריך להסיר אותו מהמפה ואז להגדיר את הקו המרוסק עצמו ל-null.
בדיקת קו מרובה
קו פוליגוני מציין סדרה של קואורדינטות כמערך של אובייקטים מסוג LatLng. הקואורדינטות האלה קובעות את הנתיב של הקו.
כדי לאחזר את הקואורדינטות, קוראים לפונקציה getPath(), שמחזירה מערך מסוג MVCArray. אפשר לבצע מניפולציות במערך ולבדוק אותו באמצעות הפעולות הבאות:
-
getAt()מחזירה אתLatLngבאינדקס נתון מבוסס-אפס. -
insertAt()מוסיפה את הערךLatLngבמיקום שנקבע לפי אינדקס שמתחיל מ-0. שימו לב שכל הקואורדינטות הקיימות בערך האינדקס הזה יועברו קדימה. -
removeAt()מסירה אתLatLngבאינדקס מסוים שמתחיל בספרה אפס.
בדוגמה הבאה מוצג אופן בניית קו פוליגוני על סמך קליקים (כדי להוסיף קודקוד, לוחצים על המפה).
TypeScript
// This example creates an interactive map which constructs a polyline based on // user clicks. Note that the polyline only appears once its path property // contains two LatLng coordinates. let poly: google.maps.Polyline; let map: google.maps.Map; function initMap(): void { map = new google.maps.Map(document.getElementById("map") as HTMLElement, { zoom: 7, center: { lat: 41.879, lng: -87.624 }, // Center the map on Chicago, USA. }); poly = new google.maps.Polyline({ strokeColor: "#000000", strokeOpacity: 1.0, strokeWeight: 3, }); poly.setMap(map); // Add a listener for the click event map.addListener("click", addLatLng); } // Handles click events on a map, and adds a new point to the Polyline. function addLatLng(event: google.maps.MapMouseEvent) { const path = poly.getPath(); // Because path is an MVCArray, we can simply append a new coordinate // and it will automatically appear. path.push(event.latLng as google.maps.LatLng); // Add a new marker at the new plotted point on the polyline. new google.maps.Marker({ position: event.latLng, title: "#" + path.getLength(), map: map, }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates an interactive map which constructs a polyline based on // user clicks. Note that the polyline only appears once its path property // contains two LatLng coordinates. let poly; let map; function initMap() { map = new google.maps.Map(document.getElementById("map"), { zoom: 7, center: { lat: 41.879, lng: -87.624 }, // Center the map on Chicago, USA. }); poly = new google.maps.Polyline({ strokeColor: "#000000", strokeOpacity: 1.0, strokeWeight: 3, }); poly.setMap(map); // Add a listener for the click event map.addListener("click", addLatLng); } // Handles click events on a map, and adds a new point to the Polyline. function addLatLng(event) { const path = poly.getPath(); // Because path is an MVCArray, we can simply append a new coordinate // and it will automatically appear. path.push(event.latLng); // Add a new marker at the new plotted point on the polyline. new google.maps.Marker({ position: event.latLng, title: "#" + path.getLength(), map: map, }); } window.initMap = initMap;
דוגמה לניסיון
התאמה אישית של קו פוליגוני
אפשר להוסיף ל-polyline תמונות מבוססות-ווקטור בצורת סמלים. בעזרת שילוב של סמלים והמחלקה PolylineOptions, יש לכם שליטה רבה על המראה והתחושה של קווים פוליגוניים במפה.
במאמר סמלים מוסבר על חיצים, קווים מקווקווים, סמלים בהתאמה אישית וסמלים מונפשים.
פוליגונים
פוליגון מייצג אזור שמוקף בנתיב סגור (או בלולאה), שמוגדר על ידי סדרת קואורדינטות.
אובייקטים מסוג Polygon דומים לאובייקטים מסוג Polyline בכך שהם מורכבים מסדרה של קואורדינטות ברצף מסודר.
פוליגונים מצוירים עם קו מתאר ומילוי. אפשר להגדיר צבעים, עוביים ושקיפויות מותאמים אישית לקצה של הפוליגון (הקו) וצבעים ושקיפויות מותאמים אישית לאזור הסגור (המילוי). צריך לציין את הצבעים בפורמט הקסדצימלי של HTML. אין תמיכה בשמות של צבעים.
אובייקטים מסוג Polygon יכולים לתאר צורות מורכבות, כולל:
- כמה אזורים לא סמוכים שמוגדרים על ידי פוליגון יחיד.
- אזורים עם חורים.
- חיתוכים של אזור אחד או יותר.
כדי להגדיר צורה מורכבת, משתמשים במצולע עם כמה נתיבים.
הערה: שכבת הנתונים מספקת דרך פשוטה לשרטוט פוליגונים. הוא מטפל בסיבוב המצולעים בשבילכם, וכך קל יותר לצייר מצולעים עם חורים. מידע נוסף מופיע במאמר בנושא שכבת הנתונים.
הוספת מצולע
אזור פוליגוני יכול לכלול כמה נתיבים נפרדים, ולכן המאפיין Polygon של אובייקט paths מציין מערך של מערכים, שכל אחד מהם הוא מסוג MVCArray. כל מערך מגדיר רצף נפרד של קואורדינטות מסודרות LatLng.
במצולעים פשוטים שמורכבים מנתיב אחד בלבד, אפשר ליצור Polygon באמצעות מערך אחד של קואורדינטות LatLng. Maps JavaScript API ימיר את המערך הפשוט למערך של מערכים בזמן היצירה, כשהוא מאחסן אותו במאפיין paths. ממשק ה-API מספק שיטה פשוטה של getPath() למצולעים שמורכבים מנתיב אחד.
המאפיין editable של הפוליגון מציין אם המשתמשים יכולים לערוך את הצורה. מידע נוסף מופיע בקטע צורות שניתנות לעריכה על ידי משתמשים שבהמשך.
באופן דומה, אפשר להגדיר את המאפיין draggable כדי לאפשר למשתמשים לגרור את הצורה.
TypeScript
// This example creates a simple polygon representing the Bermuda Triangle. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 5, center: { lat: 24.886, lng: -70.268 }, mapTypeId: "terrain", } ); // Define the LatLng coordinates for the polygon's path. const triangleCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, { lat: 25.774, lng: -80.19 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a simple polygon representing the Bermuda Triangle. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 5, center: { lat: 24.886, lng: -70.268 }, mapTypeId: "terrain", }); // Define the LatLng coordinates for the polygon's path. const triangleCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, { lat: 25.774, lng: -80.19 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } window.initMap = initMap;
דוגמה לניסיון
השלמה אוטומטית של פוליגון
הפוליגון Polygon בדוגמה שלמעלה מורכב מארבעה סטים של קואורדינטות LatLng, אבל שימו לב שהסטים הראשון והאחרון מגדירים את אותו מיקום, וכך נסגרת הלולאה. בפועל, מכיוון שמצולעים מגדירים אזורים סגורים, לא צריך לציין את קבוצת הקואורדינטות האחרונה. Maps JavaScript API ישלים אוטומטית את הפוליגון על ידי שרטוט קו שמחבר את המיקום האחרון חזרה למיקום הראשון בכל נתיב נתון.
הדוגמה הבאה זהה לדוגמה הקודמת, אבל השורה האחרונה LatLng הושמטה:
לדוגמה.
הסרת פוליגון
כדי להסיר מצולע מהמפה, קוראים ל-method setMap() ומעבירים את null כארגומנט. בדוגמה הבאה, bermudaTriangle הוא אובייקט מצולע:
bermudaTriangle.setMap(null);
חשוב לזכור שהשיטה שלמעלה לא מוחקת את הפוליגון. הפוליגון יוסר מהמפה. אם רוצים למחוק את הפוליגון, צריך להסיר אותו מהמפה ואז להגדיר את הפוליגון עצמו ל-null.
בדיקת פוליגון
פוליגון מציין את סדרת הקואורדינטות שלו כמערך של מערכים, כאשר כל מערך הוא מסוג MVCArray. כל מערך 'עלה' הוא מערך של LatLng קואורדינטות
שמציינות נתיב יחיד. כדי לאחזר את הקואורדינטות האלה, קוראים לשיטה getPaths() של האובייקט Polygon. מאחר שהמערך
הוא MVCArray, תצטרכו לשנות אותו ולבדוק אותו באמצעות הפעולות הבאות:
-
getAt()מחזירה אתLatLngבאינדקס נתון מבוסס-אפס. -
insertAt()מוסיפה את הערךLatLngבמיקום שנקבע לפי אינדקס שמתחיל מ-0. שימו לב שכל הקואורדינטות הקיימות בערך האינדקס הזה יועברו קדימה. -
removeAt()מסירה אתLatLngבאינדקס מסוים שמתחיל בספרה אפס.
TypeScript
// This example creates a simple polygon representing the Bermuda Triangle. // When the user clicks on the polygon an info window opens, showing // information about the polygon's coordinates. let map: google.maps.Map; let infoWindow: google.maps.InfoWindow; function initMap(): void { map = new google.maps.Map(document.getElementById("map") as HTMLElement, { zoom: 5, center: { lat: 24.886, lng: -70.268 }, mapTypeId: "terrain", }); // Define the LatLng coordinates for the polygon. const triangleCoords: google.maps.LatLngLiteral[] = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 3, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); // Add a listener for the click event. bermudaTriangle.addListener("click", showArrays); infoWindow = new google.maps.InfoWindow(); } function showArrays(event: any) { // Since this polygon has only one path, we can call getPath() to return the // MVCArray of LatLngs. // @ts-ignore const polygon = this as google.maps.Polygon; const vertices = polygon.getPath(); let contentString = "<b>Bermuda Triangle polygon</b><br>" + "Clicked location: <br>" + event.latLng.lat() + "," + event.latLng.lng() + "<br>"; // Iterate over the vertices. for (let i = 0; i < vertices.getLength(); i++) { const xy = vertices.getAt(i); contentString += "<br>" + "Coordinate " + i + ":<br>" + xy.lat() + "," + xy.lng(); } // Replace the info window's content and position. infoWindow.setContent(contentString); infoWindow.setPosition(event.latLng); infoWindow.open(map); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a simple polygon representing the Bermuda Triangle. // When the user clicks on the polygon an info window opens, showing // information about the polygon's coordinates. let map; let infoWindow; function initMap() { map = new google.maps.Map(document.getElementById("map"), { zoom: 5, center: { lat: 24.886, lng: -70.268 }, mapTypeId: "terrain", }); // Define the LatLng coordinates for the polygon. const triangleCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 3, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); // Add a listener for the click event. bermudaTriangle.addListener("click", showArrays); infoWindow = new google.maps.InfoWindow(); } function showArrays(event) { // Since this polygon has only one path, we can call getPath() to return the // MVCArray of LatLngs. // @ts-ignore const polygon = this; const vertices = polygon.getPath(); let contentString = "<b>Bermuda Triangle polygon</b><br>" + "Clicked location: <br>" + event.latLng.lat() + "," + event.latLng.lng() + "<br>"; // Iterate over the vertices. for (let i = 0; i < vertices.getLength(); i++) { const xy = vertices.getAt(i); contentString += "<br>" + "Coordinate " + i + ":<br>" + xy.lat() + "," + xy.lng(); } // Replace the info window's content and position. infoWindow.setContent(contentString); infoWindow.setPosition(event.latLng); infoWindow.open(map); } window.initMap = initMap;
דוגמה לניסיון
יצירת חור בפוליגון
כדי ליצור אזור ריק בתוך פוליגון, צריך ליצור שתי נתיבים, אחד בתוך השני. כדי ליצור את החור, הקואורדינטות שמגדירות את הנתיב הפנימי צריכות להיות בסדר הפוך לקואורדינטות שמגדירות את הנתיב החיצוני. לדוגמה, אם הקואורדינטות של הנתיב החיצוני הן בסדר עם כיוון השעון, הקואורדינטות של הנתיב הפנימי צריכות להיות בסדר נגד כיוון השעון.
הערה: שכבת הנתונים מטפלת בסדר של הנתיבים הפנימיים והחיצוניים, וכך קל יותר לצייר פוליגונים עם חורים. מידע נוסף מופיע במאמרי העזרה בנושא שכבת הנתונים.
בדוגמה הבאה מצויר פוליגון עם שני נתיבים, כשהנתיב הפנימי מסתובב בכיוון ההפוך לנתיב החיצוני.
TypeScript
// This example creates a triangular polygon with a hole in it. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 5, center: { lat: 24.886, lng: -70.268 }, } ); // Define the LatLng coordinates for the polygon's outer path. const outerCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Define the LatLng coordinates for the polygon's inner path. // Note that the points forming the inner path are wound in the // opposite direction to those in the outer path, to form the hole. const innerCoords = [ { lat: 28.745, lng: -70.579 }, { lat: 29.57, lng: -67.514 }, { lat: 27.339, lng: -66.668 }, ]; // Construct the polygon, including both paths. const bermudaTriangle = new google.maps.Polygon({ paths: [outerCoords, innerCoords], strokeColor: "#FFC107", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FFC107", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a triangular polygon with a hole in it. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 5, center: { lat: 24.886, lng: -70.268 }, }); // Define the LatLng coordinates for the polygon's outer path. const outerCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Define the LatLng coordinates for the polygon's inner path. // Note that the points forming the inner path are wound in the // opposite direction to those in the outer path, to form the hole. const innerCoords = [ { lat: 28.745, lng: -70.579 }, { lat: 29.57, lng: -67.514 }, { lat: 27.339, lng: -66.668 }, ]; // Construct the polygon, including both paths. const bermudaTriangle = new google.maps.Polygon({ paths: [outerCoords, innerCoords], strokeColor: "#FFC107", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FFC107", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } window.initMap = initMap;
דוגמה לניסיון
מלבנים
בנוסף למחלקה Polygon הכללית, ממשק API של JavaScript במפות Google כולל מחלקה ספציפית לאובייקטים מסוג
Rectangle, כדי לפשט את היצירה שלהם.
הוספת מלבן
Rectangle דומה ל-Polygon ב-
שבו אפשר להגדיר צבעים, משקלים ואטימויות מותאמים אישית לקצה של
המלבן (השבץ) וצבעים ואטימויות מותאמים אישית לאזור בתוך
המלבן (המילוי). צריך לציין את הצבעים בסגנון הקסדצימלי של HTML.
בניגוד לPolygon, לא מגדירים paths
לRectangle. במקום זאת, למלבן יש מאפיין bounds
שמגדיר את הצורה שלו על ידי ציון
google.maps.LatLngBounds למלבן.
המאפיין editable של המלבן קובע אם המשתמשים יכולים לערוך את הצורה. מידע נוסף מופיע בקטע צורות שאפשר לערוך שבהמשך. באופן דומה, אפשר להגדיר את המאפיין draggable כדי לאפשר למשתמשים לגרור את המלבן.
TypeScript
// This example adds a red rectangle to a map. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 11, center: { lat: 33.678, lng: -116.243 }, mapTypeId: "terrain", } ); const rectangle = new google.maps.Rectangle({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: { north: 33.685, south: 33.671, east: -116.234, west: -116.251, }, }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example adds a red rectangle to a map. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 11, center: { lat: 33.678, lng: -116.243 }, mapTypeId: "terrain", }); const rectangle = new google.maps.Rectangle({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: { north: 33.685, south: 33.671, east: -116.234, west: -116.251, }, }); } window.initMap = initMap;
דוגמה לניסיון
הקוד הבא יוצר מלבן בכל פעם שהמשתמש משנה את רמת הזום במפה: גודל המלבן נקבע לפי אזור התצוגה.
TypeScript
// This example creates a rectangle based on the viewport // on any 'zoom-changed' event. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 11, center: { lat: 40.74852, lng: -73.981687 }, mapTypeId: "terrain", } ); const rectangle = new google.maps.Rectangle(); map.addListener("zoom_changed", () => { // Get the current bounds, which reflect the bounds before the zoom. rectangle.setOptions({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: map.getBounds() as google.maps.LatLngBounds, }); }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a rectangle based on the viewport // on any 'zoom-changed' event. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 11, center: { lat: 40.74852, lng: -73.981687 }, mapTypeId: "terrain", }); const rectangle = new google.maps.Rectangle(); map.addListener("zoom_changed", () => { // Get the current bounds, which reflect the bounds before the zoom. rectangle.setOptions({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: map.getBounds(), }); }); } window.initMap = initMap;
דוגמה לניסיון
הסרת מלבן
כדי להסיר מלבן מהמפה, קוראים לשיטה setMap() ומעבירים את null כארגומנט.
rectangle.setMap(null);
חשוב לזכור שהשיטה שלמעלה לא מוחקת את המלבן. הוא מסיר את המלבן מהמפה. אם רוצים למחוק את המלבן, צריך להסיר אותו מהמפה ואז להגדיר את המלבן עצמו ל-null.
מעגלים
בנוסף למחלקה הכללית Polygon, ממשק API של JavaScript במפות Google כולל מחלקה ספציפית לאובייקטים מסוג
Circle, כדי לפשט את היצירה שלהם.
הוספת מעגל
Circle דומה ל-Polygon בכך שאפשר להגדיר צבעים, משקלים ואטימויות מותאמים אישית לקצה המעגל (הקו) וצבעים ואטימויות מותאמים אישית לאזור בתוך המעגל (המילוי). צריך לציין את הצבעים בסגנון הקסדצימלי של HTML.
בניגוד לPolygon, לא מגדירים paths
לCircle. במקום זאת, למעגל יש שני מאפיינים נוספים שמגדירים את הצורה שלו:
-
centerמציין אתgoogle.maps.LatLngשל מרכז המעגל. -
radiusמציין את רדיוס המעגל, במטרים.
המאפיין editable של הצורה circle מציין אם המשתמשים יכולים לערוך את הצורה. מידע נוסף מופיע בקטע צורות שניתנות לעריכה על ידי משתמשים שבהמשך.
באופן דומה, אתם יכולים להגדיר את המאפיין draggable כדי לאפשר למשתמשים לגרור את העיגול.
בדוגמה הבאה נעשה שימוש בעיגולים כדי להציג את משך ההליכה המשוער בין מיקומים שונים בקיוטו, יפן. בוחרים את המרחק הרצוי מהתפריט, לוחצים על המפה כדי למרכז מחדש את העיגול וגוררים את העיגול כדי לשנות את המיקום שלו.
TypeScript
const mapElement = document.querySelector('gmp-map') as google.maps.MapElement; let innerMap; async function initMap() { // Import the needed libraries. // Request needed libraries. (await google.maps.importLibrary('maps')) as google.maps.MapsLibrary; (await google.maps.importLibrary('marker')) as google.maps.MarkerLibrary; // Get the gmp-map element. const mapElement = document.querySelector( 'gmp-map' ) as google.maps.MapElement; const initialCenter = { lat: 34.98956821576194, lng: 135.74239981260283 }; // Hotel Emion, Kyoto, Japan // Get the inner map. const innerMap = mapElement.innerMap; const buttons = document.querySelectorAll('input[name="radius"]'); const walkingCircle = new google.maps.Circle({ strokeColor: '#ffdd00ff', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#ffdd00ff', fillOpacity: 0.35, map: innerMap, center: initialCenter, radius: 400, draggable: true, editable: false, }); // Define a "Crosshair" vector icon const parser = new DOMParser(); const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="-6 -6 12 12"><path d="M -6,0 L 6,0 M 0,-6 L 0,6" stroke="black" stroke-width="1"/></svg>`; const pinSvg = parser.parseFromString( svgString, 'image/svg+xml' ).documentElement; const centerMarker = new google.maps.marker.AdvancedMarkerElement({ position: initialCenter, title: 'A marker using a custom SVG image.', //@ts-ignore anchorLeft: '-50%', anchorTop: '-50%', }); centerMarker.append(pinSvg); mapElement.append(centerMarker); // Wait for the map to finish drawing its tiles. google.maps.event.addListenerOnce(innerMap, 'tilesloaded', function () { // Get the controls div const controls = document.getElementById('control-panel'); // Display controls once map is loaded. if (controls) { controls.style.display = 'block'; } }); // Add event listener to update the radius based on user selection. buttons.forEach((button) => { button.addEventListener('change', (event) => { const target = event.target as HTMLInputElement; walkingCircle.setRadius(Number(target.value)); }); }); // Handle user click, reset the map center and position the circle. innerMap.addListener('click', (mapsMouseEvent) => { const newCenter = mapsMouseEvent.latLng; walkingCircle.setCenter(newCenter); centerMarker.position = newCenter; innerMap.panTo(newCenter); }); // Handle user dragging the circle, update the center marker position. walkingCircle.addListener('center_changed', () => { centerMarker.position = walkingCircle.getCenter(); }); } initMap();
JavaScript
const mapElement = document.querySelector('gmp-map'); let innerMap; async function initMap() { // Import the needed libraries. // Request needed libraries. (await google.maps.importLibrary('maps')); (await google.maps.importLibrary('marker')); // Get the gmp-map element. const mapElement = document.querySelector('gmp-map'); const initialCenter = { lat: 34.98956821576194, lng: 135.74239981260283 }; // Hotel Emion, Kyoto, Japan // Get the inner map. const innerMap = mapElement.innerMap; const buttons = document.querySelectorAll('input[name="radius"]'); const walkingCircle = new google.maps.Circle({ strokeColor: '#ffdd00ff', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#ffdd00ff', fillOpacity: 0.35, map: innerMap, center: initialCenter, radius: 400, draggable: true, editable: false, }); // Define a "Crosshair" vector icon const parser = new DOMParser(); const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="-6 -6 12 12"><path d="M -6,0 L 6,0 M 0,-6 L 0,6" stroke="black" stroke-width="1"/></svg>`; const pinSvg = parser.parseFromString(svgString, 'image/svg+xml').documentElement; const centerMarker = new google.maps.marker.AdvancedMarkerElement({ position: initialCenter, title: 'A marker using a custom SVG image.', //@ts-ignore anchorLeft: '-50%', anchorTop: '-50%', }); centerMarker.append(pinSvg); mapElement.append(centerMarker); // Wait for the map to finish drawing its tiles. google.maps.event.addListenerOnce(innerMap, 'tilesloaded', function () { // Get the controls div const controls = document.getElementById('control-panel'); // Display controls once map is loaded. if (controls) { controls.style.display = 'block'; } }); // Add event listener to update the radius based on user selection. buttons.forEach((button) => { button.addEventListener('change', (event) => { const target = event.target; walkingCircle.setRadius(Number(target.value)); }); }); // Handle user click, reset the map center and position the circle. innerMap.addListener('click', (mapsMouseEvent) => { const newCenter = mapsMouseEvent.latLng; walkingCircle.setCenter(newCenter); centerMarker.position = newCenter; innerMap.panTo(newCenter); }); // Handle user dragging the circle, update the center marker position. walkingCircle.addListener('center_changed', () => { centerMarker.position = walkingCircle.getCenter(); }); } initMap();
CSS
/* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } #control-panel { display: none; /* Set to 'display: block' after the map loads. */ background-color: #fff; border: 2px solid #fff; border-radius: 3px; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); font-family: "Roboto", "sans-serif"; font-size: medium; margin: 10px; padding: 10px; }
HTML
<html>
<head>
<title>Circles</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<!-- 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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly"});</script>
</head>
<body>
<gmp-map
center="34.98956821576194, 135.74239981260283"
zoom="15"
map-id="DEMO_MAP_ID">
<div id="control-panel" slot="control-inline-start-block-start">
<input
id="short-walk"
type="radio"
name="radius"
value="400"
checked />
<label for="short-walk">Short Walk (~5 minutes)</label><br />
<input
id="medium-walk"
type="radio"
name="radius"
value="800" />
<label for="medium-walk">Medium Walk (~15 minutes)</label><br />
<input id="long-walk" type="radio" name="radius" value="1600" />
<label for="long-walk">Long Walk (~30 minutes) </label>
</div>
</gmp-map>
</body>
</html>דוגמה לניסיון
הסרת מעגל
כדי להסיר עיגול מהמפה, קוראים ל-method setMap() ומעבירים את null כארגומנט.
circle.setMap(null);
שימו לב: השיטה שלמעלה לא מוחקת את המעגל. הפעולה הזו תסיר את המעגל מהמפה. אם רוצים למחוק את העיגול, צריך להסיר אותו מהמפה ואז להגדיר את העיגול עצמו ל-null.
צורות שאפשר לערוך ולגרור
כשמגדירים צורה כניתנת לעריכה, מתווספות לצורה נקודות אחיזה שאפשר להשתמש בהן כדי לשנות את המיקום, הצורה והגודל שלה ישירות במפה. אפשר גם להגדיר צורה כגרירה, כדי שאנשים יוכלו להעביר אותה למקום אחר במפה.
שינויים שהמשתמש מבצע באובייקט לא נשמרים בין סשנים. אם רוצים לשמור את העריכות של המשתמש, צריך לתעד ולאחסן את המידע בעצמכם.
הגדרת צורה כניתנת לעריכה
אפשר להגדיר כל צורה (קווי פוליגון, פוליגונים, עיגולים ומלבנים) כצורה שניתנת לעריכה על ידי המשתמש, על ידי הגדרת editable לערך true באפשרויות של הצורה.
var bounds = { north: 44.599, south: 44.490, east: -78.443, west: -78.649 }; // Define a rectangle and set its editable property to true. var rectangle = new google.maps.Rectangle({ bounds: bounds, editable: true });
איך מאפשרים גרירה של צורה
כברירת מחדל, הצורה שמציירים במפה קבועה במיקום שלה. כדי לאפשר למשתמשים לגרור צורה למיקום אחר במפה, צריך להגדיר את draggable ל-true באפשרויות הצורה.
var redCoords = [ {lat: 25.774, lng: -80.190}, {lat: 18.466, lng: -66.118}, {lat: 32.321, lng: -64.757} ]; // Construct a draggable red triangle with geodesic set to true. new google.maps.Polygon({ map: map, paths: redCoords, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35, draggable: true, geodesic: true });
כשמפעילים גרירה של פוליגון או קו פוליגוני, כדאי גם להגדיר את הפוליגון או הקו הפוליגוני כגיאודזי, על ידי הגדרת המאפיין geodesic
שלו ל-true.
מצולע גאודזי שומר על הצורה הגיאוגרפית האמיתית שלו כשמזיזים אותו, ולכן הוא נראה מעוות כשמזיזים אותו צפונה או דרומה בהטלת מרקטור. מצולעים לא גיאודזיים תמיד ישמרו על המראה הראשוני שלהם במסך.
בקו פוליגוני גאודזי, הקטעים של הקו הפוליגוני מצוירים כנתיב הקצר ביותר בין שתי נקודות על פני כדור הארץ, בהנחה שכדור הארץ הוא ספירה, בניגוד לקווים ישרים בהטלת מרקטור.
למידע נוסף על מערכות קואורדינטות, אפשר לעיין במדריך בנושא קואורדינטות של מפות ומשבצות.
במפה הבאה מוצגים שני משולשים בגודל ובמידות דומים. המאפיין geodesic של המשולש האדום מוגדר לערך
true. שימו לב איך הצורה שלו משתנה כשהוא נע צפונה.
האזנה לאירועי עריכה
כשעורכים צורה, מופעל אירוע בסיום העריכה. האירועים האלה מפורטים בהמשך.
| צורה | אירועים |
|---|---|
| מעגל |
radius_changedcenter_changed
|
| פוליגון |
insert_atremove_atset_at
צריך להגדיר את ה-listener בנתיב של הפוליגון. אם למצולע יש כמה נתיבים, צריך להגדיר מאזין לכל נתיב. |
| מצולע פתוח |
insert_atremove_atset_at
צריך להגדיר את ה-listener בנתיב של הקו המקוטע. |
| מלבן | bounds_changed |
כמה קטעי קוד שימושיים:
google.maps.event.addListener(circle, 'radius_changed', function() { console.log(circle.getRadius()); }); google.maps.event.addListener(outerPath, 'set_at', function() { console.log('Vertex moved on outer path.'); }); google.maps.event.addListener(innerPath, 'insert_at', function() { console.log('Vertex removed from inner path.'); }); google.maps.event.addListener(rectangle, 'bounds_changed', function() { console.log('Bounds changed.'); });
דוגמה לטיפול באירוע עריכה של מלבן
האזנה לאירועי גרירה
כשגוררים צורה, מופעלים אירועים בתחילת פעולת הגרירה ובסופה, וגם במהלך הגרירה. האירועים הבאים מופעלים עבור קווים פוליגוניים, מצולעים, עיגולים ומלבנים.
| אירוע | תיאור |
|---|---|
dragstart |
מופעל כשהמשתמש מתחיל לגרור את הצורה. |
drag |
מופעל שוב ושוב בזמן שהמשתמש גורר את הצורה. |
dragend |
מופעל כשהמשתמש מפסיק לגרור את הצורה. |
מידע נוסף על טיפול באירועים זמין במאמרי העזרה בנושא אירועים.