צורות

בחירת פלטפורמה: Android iOS JavaScript

אפשר להוסיף למפה צורות שונות. צורה היא אובייקט במפה, שקשור לקואורדינטה של קווי אורך/רוחב. הצורות הזמינות הן: קווים, פוליגונים, מעגלים ומלבנים. אפשר גם להגדיר את הצורות כך שהמשתמשים יוכלו לערוך או לגרור אותן.

קווים מרובים

כדי לשרטט קו במפה, אפשר להשתמש בקו פוליגוני. המחלקה Polyline מגדירה שכבת-על לינארית של קטעי קו מחוברים במפה. אובייקט Polyline מורכב ממערך של LatLng מיקומים, ויוצר סדרה של קטעי קו שמחברים בין המיקומים האלה ברצף מסודר.

הוספת קו פוליגוני

הבנאי Polyline לוקח קבוצה של 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;
להצגת דוגמה

רוצה לנסות דוגמה?

הסרת קו פוליגוני

כדי להסיר קו מרובה מהמפה, צריך לקרוא ל-method setMap() בהעברת null כארגומנט. בדוגמה הבאה, flightPath הוא אובייקט polyline:

flightPath.setMap(null);

שימו לב שהשיטה שלמעלה לא מוחקת את הקו. הפעולה הזו מסירה את הקו הפוליגוני מהמפה. כדי למחוק את הקו הפוליגוני, צריך להסיר אותו מהמפה ולהגדיר את הקו הפוליגוני עצמו ל-null.

בדיקת קו פוליגוני

קו פוליגוני מציין סדרת קואורדינטות כמערך של LatLng אובייקטים. קואורדינטות אלה קובעות את נתיב הקו. כדי לאחזר את הקואורדינטות, צריך לבצע קריאה ל-getPath(), שתחזיר מערך מסוג MVCArray. אפשר לבצע את הפעולות הבאות ולבדוק את המערך:

  • getAt() מחזירה את LatLng בערך נתון של אינדקס מבוסס אפס.
  • insertAt() מוסיפה LatLng שעבר בערך נתון לאינדקס מבוסס-אפס. שימו לב שכל הקואורדינטות הקיימות בערך האינדקס הזה מועברות קדימה.
  • 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;
להצגת דוגמה

רוצה לנסות דוגמה?

התאמה אישית של קו פוליגוני

אפשר להוסיף תמונות המבוססות על וקטור לקופוליון בצורת סמלים. השילוב של הסמלים והמחלקה PolylineOptions נותן לכם שליטה רבה על המראה והתחושה של קווים מרובים במפה. בקטע סמלים ניתן למצוא מידע על arrows, קווים מקווקווים, סמלים מותאמים אישית וסמלים עם אנימציה.

מצולעים

פוליגון מייצג שטח שמוקף בנתיב סגור (או לולאה), שמוגדר על ידי סדרת קואורדינטות. Polygon אובייקטים דומים ל-Polyline אובייקטים בכך שהם מורכבים מסדרה של קואורדינטות ברצף מסודר. מצולעים משורטטים עם קו ומילוי. אפשר להגדיר צבעים, משקולות ושקיפות – בהתאמה אישית בשביל קצה הפוליגון (הקו) וצבעים ושקיפות מותאמים אישית לאזור המוקף (המילוי). יש לציין את הצבעים בפורמט HTML הקסדצימלי. שמות של צבעים אינם נתמכים.

Polygon אובייקטים יכולים לתאר צורות מורכבות, כולל:

  • כמה אזורים לא רציפים שמוגדרים על ידי פוליגון אחד.
  • אזורים עם חורים.
  • צמתים של אזור אחד או יותר.

כדי להגדיר צורה מורכבת, צריך להשתמש בפוליגון עם מספר נתיבים.

הערה: שכבת הנתונים מאפשרת לשרטט פוליגונים בקלות. הוא מטפל בפוליגונים שמתפתלים בשבילך, וכך קל יותר לשרטט פוליגונים עם חורים. עיינו במסמכי התיעוד של שכבת הנתונים.

הוספת מצולע

אזור פוליגון עשוי לכלול כמה נתיבים נפרדים, ולכן המאפיין paths של האובייקט Polygon מציין מערך של מערכים, שכל אחד מהם הוא מסוג MVCArray. כל מערך מגדיר רצף נפרד של קואורדינטות LatLng בסדר.

בפוליגונים פשוטים שמכילים רק דרך אחת, אפשר ליצור Polygon באמצעות מערך יחיד של קואורדינטות LatLng. ה-API של JavaScript של מפות Google ממיר את המערך הפשוט למערך מערכים בזמן היצירה, כאשר מאחסנים אותו בתוך הנכס 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 האחרונה חסרה: view example.

הסרת פוליגון

כדי להסיר פוליגון מהמפה, צריך לקרוא ל-method setMap() ולהעביר את null כארגומנט. בדוגמה הבאה, bermudaTriangle הוא אובייקט של פוליגון:

bermudaTriangle.setMap(null);

הערה: השיטה שלמעלה לא מוחקת את הפוליגון. הפוליגון יוסר מהמפה. כדי למחוק את הפוליגון צריך להסיר אותו מהמפה, ואז להגדיר את הפוליגון עצמו לערך null.

בדיקת פוליגון

פוליגון מציין את סדרת הקואורדינטות שלו כמערך של מערכים, כאשר כל מערך הוא מסוג MVCArray. כל מערך "leaf" הוא מערך של קואורדינטות LatLng שמציינות נתיב יחיד. כדי לאחזר את הקואורדינטות האלה, צריך לקרוא ל-method getPaths() של האובייקט Polygon. מכיוון שהמערך הוא MVCArray, צריך לשנות ולבדוק אותו באמצעות הפעולות הבאות:

  • getAt() מחזירה את LatLng בערך נתון של אינדקס מבוסס אפס.
  • insertAt() מוסיפה LatLng שעבר בערך נתון לאינדקס מבוסס-אפס. שימו לב שכל הקואורדינטות הקיימות בערך האינדקס הזה מועברות קדימה.
  • 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 כללית, Google Maps JavaScript API כולל מחלקה ספציפית עבור 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;
להצגת דוגמה

רוצה לנסות דוגמה?

הסרת מלבן

כדי להסיר מלבן מהמפה, צריך לקרוא ל-method setMap() ולהעביר את null כארגומנט.

rectangle.setMap(null);

הערה: השיטה שלמעלה לא מוחקת את המלבן. המלבן יוסר מהמפה. אם במקום זאת ברצונך למחוק את המלבן, עליך להסיר אותו מהמפה ולהגדיר את המלבן עצמו ל-null.

עיגולים

בנוסף למחלקה Polygon הגנרית, Google Maps JavaScript API כולל מחלקה ספציפית עבור Circle אובייקטים, כדי לפשט את הבנייה שלהם.

הוספת מעגל

Circle דומה ל-Polygon בכך שניתן להגדיר צבעים, משקולות אטימציות מותאמים אישית עבור קצה העיגול (הקו) וצבעים ושקיפות מותאמים אישית עבור האזור שבתוך העיגול (המילוי). יש לציין את הצבעים בסגנון HTML מספרי הקסדצימלי.

בניגוד ל-Polygon, אין צורך להגדיר את paths עבור Circle. במקום זאת, לעיגול יש שני מאפיינים נוספים שמגדירים את הצורה שלו:

  • center מציין את ה-google.maps.LatLng של מרכז המעגל.
  • radius מציין את רדיוס המעגל במטרים.

המאפיין editable של העיגול מציין אם משתמשים יכולים לערוך את הצורה. מידע נוסף מופיע בקטע צורות הניתנות לעריכה על ידי המשתמש שבהמשך. באופן דומה, אפשר להגדיר את המאפיין draggable כדי לאפשר למשתמשים לגרור את המעגל.

TypeScript

// This example creates circles on the map, representing populations in North
// America.

// First, create an object containing LatLng and population for each city.

interface City {
  center: google.maps.LatLngLiteral;
  population: number;
}

const citymap: Record<string, City> = {
  chicago: {
    center: { lat: 41.878, lng: -87.629 },
    population: 2714856,
  },
  newyork: {
    center: { lat: 40.714, lng: -74.005 },
    population: 8405837,
  },
  losangeles: {
    center: { lat: 34.052, lng: -118.243 },
    population: 3857799,
  },
  vancouver: {
    center: { lat: 49.25, lng: -123.1 },
    population: 603502,
  },
};

function initMap(): void {
  // Create the map.
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: { lat: 37.09, lng: -95.712 },
      mapTypeId: "terrain",
    }
  );

  // Construct the circle for each value in citymap.
  // Note: We scale the area of the circle based on the population.
  for (const city in citymap) {
    // Add the circle for this city to the map.
    const cityCircle = new google.maps.Circle({
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#FF0000",
      fillOpacity: 0.35,
      map,
      center: citymap[city].center,
      radius: Math.sqrt(citymap[city].population) * 100,
    });
  }
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

const citymap = {
  chicago: {
    center: { lat: 41.878, lng: -87.629 },
    population: 2714856,
  },
  newyork: {
    center: { lat: 40.714, lng: -74.005 },
    population: 8405837,
  },
  losangeles: {
    center: { lat: 34.052, lng: -118.243 },
    population: 3857799,
  },
  vancouver: {
    center: { lat: 49.25, lng: -123.1 },
    population: 603502,
  },
};

function initMap() {
  // Create the map.
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: 37.09, lng: -95.712 },
    mapTypeId: "terrain",
  });

  // Construct the circle for each value in citymap.
  // Note: We scale the area of the circle based on the population.
  for (const city in citymap) {
    // Add the circle for this city to the map.
    const cityCircle = new google.maps.Circle({
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#FF0000",
      fillOpacity: 0.35,
      map,
      center: citymap[city].center,
      radius: Math.sqrt(citymap[city].population) * 100,
    });
  }
}

window.initMap = initMap;
להצגת דוגמה

רוצה לנסות דוגמה?

הסרת מעגל

כדי להסיר מעגל מהמפה, צריך לקרוא ל-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.

מצולע גיאודזי ישמור על צורתו הגיאוגרפית האמיתית בעת תזוזה, ויגרום לפוליגון להיראות מעוות כאשר הוא זז צפונה או דרומה בהיטל המרקטור. מצולעים לא גיאוגרפיים תמיד ישמרו על המראה הראשוני שלהם על המסך.

בקו מרובה גיאודזי, הקטעים של קו הפוליגון משורטטים כנתיב הקצר ביותר בין שתי נקודות על פני השטח של כדור הארץ, בהנחה שכדור הארץ הוא כדור, בניגוד לקווים ישרים בהיטל ה-Mercator.

למידע נוסף על מערכות קואורדינטות, אפשר לעיין במדריך בנושא קואורדינטות של מיפוי ומשבצות.

במפה הבאה מוצגים שני משולשים בערך באותו גודל ובאותה מידות. במשולש האדום מוגדרת המאפיין geodesic של true. שימו לב איך הצורה משתנה כשהיא נעה צפונה.

להצגת דוגמה

האזנה לעריכת אירועים

כאשר מתבצעת עריכה של צורה, אירוע מופעל בסיום העריכה. האירועים האלה מפורטים בהמשך.

צורה אירועים
מעגל radius_changed
center_changed
פוליגון insert_at
remove_at
set_at

יש להגדיר את ה-listener בנתיב של הפוליגון. אם לפוליגון יש כמה נתיבים, צריך להגדיר listener לכל נתיב.

מצולע פתוח insert_at
remove_at
set_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 מופעל כשהמשתמש מפסיק לגרור את הצורה.

מידע נוסף על טיפול באירועים זמין במסמכי התיעוד בנושא אירועים.