צורות וקווים

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

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

קווים פוליגוניים

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

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

ה-constructor של 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;
להצגת דוגמה

כדאי לנסות דוגמה

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

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

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

הדוגמה הבאה זהה לזו הקודמת, מלבד שה-LatLng האחרון לא מופיע: view example.

הסרת פוליגון

כדי להסיר פוליגון מהמפה, צריך להפעיל את השיטה 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 כללית, ה-JavaScript API של מפות 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, ה-JavaScript API של מפות Google כולל מחלקה ספציפית לאובייקטים מסוג 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;
להצגת דוגמה

כדאי לנסות דוגמה

הסרת מעגל

כדי להסיר מעגל מהמפה, צריך להפעיל את השיטה 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. פוליגונים לא גיאוגרפיים תמיד ישמרו על המראה הראשוני שלהם במסך.

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

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

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

להצגת דוגמה

איך מקשיבים לעריכת אירועים

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

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

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

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