도형

플랫폼 선택: Android iOS 자바스크립트

지도에 다양한 도형을 추가할 수 있습니다. 도형은 위도/경도 좌표와 연결된 지도 위의 객체입니다. , 다각형, , 직사각형 등의 도형을 사용할 수 있습니다. 사용자가 수정하거나 드래그할 수 있도록 도형을 구성할 수도 있습니다.

다중선

지도에 선을 그리려면 다중선을 사용하세요. Polyline 클래스는 지도에서 연결된 선분의 선형 오버레이를 정의합니다. Polyline 객체는 일련의 LatLng 위치로 구성되며 그러한 위치를 순서대로 연결하는 일련의 선분을 생성합니다.

다중선 추가

Polyline 생성자는 선의 LatLng 좌표를 지정하는 PolylineOptions의 집합과 스타일의 집합을 가져와 다중선의 시각적인 동작을 조정합니다.

Polyline 객체는 지도에 일련의 직선 선분으로 그려집니다. 선을 생성할 때 PolylineOptions 내에서 선 획의 맞춤 색상, 두께 및 불투명도를 지정하거나 생성 후 이러한 속성을 변경할 수 있습니다. 다중선에는 다음과 같은 획 스타일을 사용할 수 있습니다.

  • strokeColor"#FFFFFF" 형식의 16진수 HTML 색상을 지정합니다. Polyline 클래스는 이름이 지정된 색상을 지원하지 않습니다.
  • strokeOpacity0.01.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;
예시 보기

샘플 사용해 보기

다중선 제거

지도에서 다중선을 제거하려면 null을 인수로 전달하는 setMap() 메서드를 호출하세요. 다음 예에서는 flightPath가 다중선 객체입니다.

flightPath.setMap(null);

위의 메서드는 다중선을 삭제하지 않으며 지도에서 다중선을 제거할 뿐입니다. 다중선을 삭제하려면 지도에서 제거한 다음 다중선 자체를 null로 설정해야 합니다.

다중선 검사

다중선은 일련의 좌표를 LatLng 객체의 배열로 지정합니다. 이러한 좌표가 선의 경로를 결정합니다. 좌표를 가져오려면 MVCArray 유형의 배열을 반환하는 getPath()를 호출하세요. 다음 작업을 통해 배열을 조작하고 검사할 수 있습니다.

  • getAt()은 0에서 시작하는 지정된 색인 값에서 LatLng를 반환합니다.
  • insertAt()은 0에서 시작하는 지정된 색인 값에 전달된 LatLng를 삽입합니다. 해당 색인 값의 기존 좌표는 앞으로 이동합니다.
  • removeAt()은 0에서 시작하는 지정된 색인 값에서 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 클래스의 조합을 사용하면 지도에서 다중선의 디자인 및 느낌을 다양하게 제어할 수 있습니다. 화살표, 점선, 맞춤 기호, 애니메이션 기호에 관한 자세한 내용은 기호를 참고하세요.

다각형

다각형은 일련의 좌표로 정의되는 닫힌 경로(또는 루프)로 둘러싸인 영역을 나타냅니다. Polygon 객체는 순서가 지정된 일련의 좌표로 이루어졌다는 점에서 Polyline 객체와 유사합니다. 다각형은 획과 채우기로 그려집니다. 다각형 가장자리(획)의 맞춤 색상, 두께 및 불투명도와 둘러싸인 영역(채우기)의 맞춤 색상 및 불투명도를 정의할 수 있습니다. 색상은 16진수 HTML 형식으로 표시해야 합니다. 색상 이름은 지원되지 않습니다.

Polygon 객체로 다음과 같이 복잡한 도형을 표시할 수 있습니다.

  • 단일 다각형으로 정의된 인접하지 않은 여러 영역
  • 구멍이 있는 영역
  • 영역 하나 이상의 교차 영역

복잡한 도형을 정의하려면 여러 경로가 포함된 다각형을 사용하세요.

참고: 데이터 영역을 사용하면 간단하게 다각형을 그릴 수 있습니다. 데이터 영역에서 다각형 와인딩을 처리하므로 구멍이 있는 다각형을 쉽게 그릴 수 있습니다. 데이터 영역 문서를 참고하세요.

다각형 추가

다각형 영역에 여러 개의 개별 경로가 포함될 수 있으므로 Polygon 객체의 paths 속성은 각각 MVCArray 유형인 배열의 배열을 지정합니다. 각 배열은 순서가 지정된 LatLng 좌표의 개별 시퀀스를 정의합니다.

하나의 경로로만 구성된 간단한 다각형의 경우 LatLng 좌표의 단일 배열을 사용하여 Polygon을 생성할 수 있습니다. 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가 생략된 것을 제외하고는 이전 예와 동일합니다. 예 보기

다각형 제거

지도에서 다각형을 제거하려면 null을 인수로 전달하는 setMap() 메서드를 호출하세요. 다음 예에서는 bermudaTriangle이 다각형 객체입니다.

bermudaTriangle.setMap(null);

위의 메서드는 다각형을 삭제하지 않으며 지도에서 다각형을 제거합니다. 다각형을 삭제하려면 지도에서 제거한 다음 다각형 자체를 null로 설정해야 합니다.

다각형 검사

다각형은 일련의 좌표를 각각 MVCArray 유형인 배열의 배열로 지정합니다. 각 '리프' 배열은 단일 경로를 지정하는 LatLng 좌표의 배열입니다. 이 좌표를 가져오려면 Polygon 객체의 getPaths() 메서드를 호출하세요. 배열은 MVCArray이므로 다음 작업을 통해 배열을 처리하고 검사해야 합니다.

  • getAt()은 0에서 시작하는 지정된 색인 값에서 LatLng를 반환합니다.
  • insertAt()은 0에서 시작하는 지정된 색인 값에 전달된 LatLng를 삽입합니다. 해당 색인 값의 기존 좌표는 앞으로 이동합니다.
  • removeAt()은 0에서 시작하는 지정된 색인 값에서 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;
예시 보기

샘플 사용해 보기

직사각형

Google Maps JavaScript API에는 일반 Polygon 클래스 외에 Rectangle 객체의 생성을 단순화하기 위한 특정 클래스가 포함되어 있습니다.

직사각형 추가

Rectangle은 직사각형 가장자리(획)의 맞춤 색상, 두께, 불투명도와 직사각형 내부 영역(채우기)의 맞춤 색상 및 불투명도를 정의할 수 있다는 점에서 Polygon과 유사합니다. 색상은 16진수 HTML 형식으로 표시해야 합니다.

Polygon과 달리 Rectanglepaths는 정의하지 않습니다. 대신 직사각형에는 직사각형의 google.maps.LatLngBounds를 지정하여 모양을 정의하는 bounds 속성이 있습니다.

직사각형의 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;
예시 보기

샘플 사용해 보기

직사각형 제거

지도에서 직사각형을 제거하려면 null을 인수로 전달하는 setMap() 메서드를 호출하세요.

rectangle.setMap(null);

위의 메서드는 직사각형을 삭제하지 않으며 지도에서 직사각형을 제거할 뿐입니다. 직사각형을 삭제하려면 지도에서 제거한 다음 직사각형 자체를 null로 설정해야 합니다.

Google Maps JavaScript API에는 일반 Polygon 클래스 외에 Circle 객체의 생성을 단순화하기 위한 특정 클래스가 포함되어 있습니다.

원 추가

Circle은 원 가장자리(획)의 맞춤 색상, 두께, 불투명도와 원 내부 영역(채우기)의 맞춤 색상 및 불투명도를 정의할 수 있다는 점에서 Polygon과 유사합니다. 색상은 16진수 HTML 형식으로 표시해야 합니다.

Polygon과 달리 Circlepaths는 정의하지 않습니다. 대신 원에는 원의 모양을 정의하는 두 가지 추가 속성이 있습니다.

  • 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;
예시 보기

샘플 사용해 보기

원 제거

지도에서 원을 제거하려면 null을 인수로 전달하는 setMap() 메서드를 호출하세요.

circle.setMap(null);

위의 메서드는 원을 삭제하지 않으며 지도에서 원을 제거합니다. 원을 삭제하려면 지도에서 제거한 다음 원 자체를 null로 설정해야 합니다.

사용자가 수정하고 드래그할 수 있는 도형

도형을 수정 가능하도록 만들면 도형에 핸들이 추가되며, 이 핸들을 사용하면 지도에서 직접 도형의 위치와 형태, 크기를 변경할 수 있습니다. 사용자가 도형을 지도의 다른 장소로 이동할 수 있도록 드래그 가능하도록 만들 수도 있습니다.

사용자가 객체에 적용한 변경사항은 세션 간에 유지되지 않습니다. 사용자가 수정한 사항을 저장하려면 직접 정보를 캡처하고 저장해야 합니다.

도형을 수정 가능하도록 만들기

모든 도형(다중선, 다각형, 원 및 직사각형)은 도형의 옵션에서 editabletrue로 설정하여 사용자가 수정 가능하도록 설정할 수 있습니다.

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
});

예 보기

도형을 드래그 가능하도록 만들기

기본적으로 지도에 그려지는 도형은 위치가 고정됩니다. 사용자가 도형을 지도의 다른 위치로 드래그할 수 있도록 하려면 도형 옵션에서 draggabletrue로 설정하세요.

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_changed
center_changed
다각형 insert_at
remove_at
set_at

리스너는 다각형의 경로에 설정해야 합니다. 다각형에 여러 경로가 있으면 각 경로에 리스너를 설정해야 합니다.

다중선 insert_at
remove_at
set_at

리스너는 다중선의 경로에 설정해야 합니다.

직사각형 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 사용자가 도형 드래그를 중지하면 실행됩니다.

이벤트 처리에 대한 자세한 내용은 이벤트 문서를 참고하세요.