도형 및 선

플랫폼 선택: Android iOS

지도에 다양한 도형을 추가할 수 있습니다. 도형은 LatLng 좌표계에 연결된 지도 위의 객체입니다. Maps JavaScript API의 3D 지도에서는 지도에 선과 다각형을 추가할 수 있습니다.

다중선

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

다중선 추가

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

다중선 객체는 지도에 일련의 직선 선분으로 그려집니다. 선을 생성할 때 Polyline3DElementOptions 내에서 선 획의 사용자 지정 색상, 너비, 불투명도, 높이, 기하학적 스타일 지정 옵션을 지정하거나 생성 후 이러한 속성을 변경할 수 있습니다. 다중선에는 다음과 같은 획 스타일을 사용할 수 있습니다.

  • outerColor: "#FFFFFF" 형식의 16진수 HTML 색상입니다.
  • outerWidth: strokeWidth의 백분율로 해석되는 0.0~1.0 사이의 숫자 값입니다.
  • strokeColor: "#FFFFFF" 형식의 16진수 HTML 색상입니다.
  • strokeWidth: 선의 너비(픽셀)입니다.
  • geodesic: 다각형의 가장자리가 지구의 곡률을 따르는지 또는 직선으로 그려지는지 여부입니다.
  • altitudeMode: 좌표의 고도 구성요소가 해석되는 방식입니다.
  • drawsOccludedSegments: 건물과 같은 객체로 가려진 다각형 부분을 그려야 하는지 나타내는 불리언입니다.
  • extruded: 다중선을 지면에 연결해야 하는지 나타내는 불리언입니다.

let map;
async function init() {
    const { Map3DElement, Polyline3DElement } =
        await google.maps.importLibrary('maps3d');

    map = new Map3DElement({
        center: { lat: 37.7927, lng: -122.402, altitude: 65.93 },
        range: 3362.87,
        tilt: 64.01,
        heading: 25.0,
        mode: 'SATELLITE',
        gestureHandling: 'COOPERATIVE',
    });

    document.body.append(map);

    const polyline = new Polyline3DElement({
        path: [
            { lat: 37.80515638571346, lng: -122.4032569467164 },
            { lat: 37.80337073509504, lng: -122.4012878349353 },
            { lat: 37.79925208843463, lng: -122.3976697250461 },
            { lat: 37.7989102378512, lng: -122.3983408725656 },
            { lat: 37.79887832784348, lng: -122.3987094864192 },
            { lat: 37.79786443410338, lng: -122.4066878788802 },
            { lat: 37.79549248916587, lng: -122.4032992702785 },
            { lat: 37.78861484290265, lng: -122.4019489189814 },
            { lat: 37.78618687561075, lng: -122.398969592545 },
            { lat: 37.7892310309145, lng: -122.3951458683092 },
            { lat: 37.7916358762409, lng: -122.3981969390652 },
        ],
        strokeColor: 'blue',
        outerColor: 'white',
        strokeWidth: 10,
        outerWidth: 0.4,
        altitudeMode: 'RELATIVE_TO_GROUND', // Place it on the ground (as it has no altitude it will just be at ground height).
        drawsOccludedSegments: true, // Show the line through the buildings or anything else that might get in the way.
    });

    map.append(polyline);
}

void init();

대화형 다중선

다음 예는 클릭 이벤트를 등록한 후 다중선의 drawsOccludedSegments 속성을 전환합니다.

let map;
async function init() {
    const { Map3DElement, Polyline3DInteractiveElement } =
        await google.maps.importLibrary('maps3d');

    map = new Map3DElement({
        center: { lat: 37.7927, lng: -122.402, altitude: 65.93 },
        range: 3362.87,
        tilt: 64.01,
        heading: 25.0,
        mode: 'SATELLITE',
        gestureHandling: 'COOPERATIVE',
    });

    document.body.append(map);

    const polyline = new Polyline3DInteractiveElement({
        coordinates: [
            { lat: 37.80515638571346, lng: -122.4032569467164 },
            { lat: 37.80337073509504, lng: -122.4012878349353 },
            { lat: 37.79925208843463, lng: -122.3976697250461 },
            { lat: 37.7989102378512, lng: -122.3983408725656 },
            { lat: 37.79887832784348, lng: -122.3987094864192 },
            { lat: 37.79786443410338, lng: -122.4066878788802 },
            { lat: 37.79549248916587, lng: -122.4032992702785 },
            { lat: 37.78861484290265, lng: -122.4019489189814 },
            { lat: 37.78618687561075, lng: -122.398969592545 },
            { lat: 37.7892310309145, lng: -122.3951458683092 },
            { lat: 37.7916358762409, lng: -122.3981969390652 },
        ],
        strokeColor: 'blue',
        outerColor: 'white',
        strokeWidth: 10,
        outerWidth: 0.4,
        altitudeMode: 'RELATIVE_TO_GROUND', // Place it on the ground (as it has no altitude it will just be at ground height).
        drawsOccludedSegments: true, // Show the line through the buildings or anything else that might get in the way.
    });

    polyline.addEventListener('gmp-click', function () {
        // Toggle whether the line draws occluded segments.
        this.drawsOccludedSegments = !this.drawsOccludedSegments;
    });

    map.append(polyline);
}

void init();

다각형

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

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

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

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

다각형 추가

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

하나의 경로로만 구성된 기본 다각형의 경우 LatLng 좌표의 단일 배열을 사용하여 Polygon3DElement를 생성할 수 있습니다. Maps JavaScript API의 3D 지도는 배열이 path 속성 내에 저장되는 경우 생성되는 즉시 배열의 배열로 변환합니다.

async function init() {
    const { Map3DElement, Polygon3DElement } =
        await google.maps.importLibrary('maps3d');

    const map3DElement = new Map3DElement({
        center: { lat: 40.6842, lng: -74.0019, altitude: 1000 },
        heading: 340,
        tilt: 70,
        mode: 'HYBRID',
        gestureHandling: 'COOPERATIVE',
    });

    const polygonOptions = {
        strokeColor: '#0000ff80',
        strokeWidth: 8,
        fillColor: '#ff000080',
        drawsOccludedSegments: false,
    };

    const examplePolygon = new Polygon3DElement(polygonOptions);

    examplePolygon.path = [
        { lat: 40.7144, lng: -74.0208 },
        { lat: 40.6993, lng: -74.019 },
        { lat: 40.7035, lng: -74.0004 },
    ];

    map3DElement.append(examplePolygon);

    document.body.append(map3DElement);
}

void init();

대화형 다각형

다음 예는 클릭 이벤트를 등록한 후 다각형의 내부 및 외부 색상을 변경합니다.

async function init() {
    const { Map3DElement, Polygon3DInteractiveElement } =
        await google.maps.importLibrary('maps3d');

    const map = new Map3DElement({
        center: { lat: 40.6842, lng: -74.0019, altitude: 1000 },
        heading: 340,
        tilt: 70,
        mode: 'HYBRID',
        gestureHandling: 'COOPERATIVE',
    });

    document.body.append(map);

    const polygonOptions = {
        strokeColor: '#0000ff80',
        strokeWidth: 8,
        fillColor: '#ff000080',
        drawsOccludedSegments: false,
    };

    const examplePolygon = new Polygon3DInteractiveElement(polygonOptions);

    examplePolygon.path = [
        { lat: 40.7144, lng: -74.0208 },
        { lat: 40.6993, lng: -74.019 },
        { lat: 40.7035, lng: -74.0004 },
        { lat: 40.7144, lng: -74.0208 },
    ];

    examplePolygon.addEventListener('gmp-click', function (event) {
        // change the color of the polygon stroke and fill colors to a random alternatives!
        this.fillColor = randomizeHexColor(this.fillColor);
        this.strokeColor = randomizeHexColor(this.strokeColor);
        console.log(event);
    });

    map.append(examplePolygon);
}

function randomizeHexColor(originalHexColor) {
    console.log(originalHexColor);
    const alpha = originalHexColor.substring(7);

    // Generate random values for Red, Green, Blue (0-255)
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);

    console.log(r + ' ' + g + ' ' + b);

    // Convert decimal to 2-digit hex, padding with '0' if needed
    const rHex = ('0' + r.toString(16)).slice(-2);
    const gHex = ('0' + g.toString(16)).slice(-2);
    const bHex = ('0' + b.toString(16)).slice(-2);

    // Combine parts: '#' + random RGB + original Alpha (if any)
    return `#${rHex}${gHex}${bHex}${alpha}`;
}

void init();