Google 지도의 데이터 영역은 임의의 지리 공간 데이터를 위한 컨테이너를 제공합니다. 데이터 영역을 사용하여 맞춤 데이터를 저장하거나 Google 지도에 GeoJSON 데이터를 표시할 수 있습니다.
개요
이 DevBytes 동영상에서 데이터 영역에 대해 자세히 알아보세요.
Maps JavaScript API를 사용하면 마커, 다중선, 다각형 등 다양한 오버레이로 지도를 마크업할 수 있습니다. 이러한 각 주석은 스타일 지정 정보를 위치 데이터와 결합합니다. google.maps.Data 클래스는 임의의 지리 공간 데이터를 위한 컨테이너입니다. 이러한 오버레이를 추가하는 대신 데이터 영역을 사용하여 임의의 지리적 데이터를 지도에 추가할 수 있습니다. 해당 데이터에 점 선, 다각형과 같은 도형이 포함되어 있으면 API가 기본적으로 이러한 도형을 마커, 다중선, 다각형으로 렌더링합니다. 이러한 지형지물의 스타일을 일반 오버레이처럼 지정하거나 데이터 세트에 포함된 다른 속성을 기반으로 스타일 지정 규칙을 적용할 수 있습니다.
google.maps.Data 클래스를 사용하면 다음과 같은 작업을 처리할 수 있습니다.
- 지도에 다각형 그리기
- 지도에 GeoJSON 데이터 추가
GeoJSON은 인터넷의 지리 공간 데이터 표준입니다.Data클래스는 데이터 표현 시 GeoJSON 구조를 따르며 이 클래스를 사용하면 GeoJSON 데이터를 쉽게 표시할 수 있습니다.loadGeoJson()메서드를 사용하면 GeoJSON 데이터를 쉽게 가져오고 점, 선 문자열, 다각형을 표시할 수 있습니다. google.maps.Data를 사용하여 임의의 데이터 모델링
대부분의 실제 항목에는 다른 속성이 연결되어 있습니다. 예를 들어 매장에는 영업시간이 있고 도로에는 속도 제한이 있고 각 걸스카우트 조직에는 쿠키 판매 구역이 있습니다.google.maps.Data를 사용하면 이러한 속성을 모델링하고 그에 따라 데이터의 스타일을 지정할 수 있습니다.- 데이터가 표시되는 방식 선택 및 즉시 방식 변경
데이터 영역을 사용하면 데이터의 시각화 및 상호작용에 대한 결정을 내릴 수 있습니다. 예를 들어 편의점 지도를 볼 때 대중교통 승차권을 판매하는 매장만 표시할 수도 있습니다.
다각형 그리기
Data.Polygon 클래스는 다각형 와인딩을 자동으로 처리합니다. 위도/경도 좌표로 정의된 하나 이상의 선형 링의 배열을 이 클래스에 전달할 수 있습니다. 첫 번째 선형 링은 다각형의 외부 경계를 정의합니다. 두 개 이상의 선형 링을 전달하는 경우 두 번째 이후의 선형 링은 다각형의 내부 경로(구멍)를 정의하는 데 사용됩니다.
다음 예에서는 안에 두 개의 구멍이 있는 직사각형을 만듭니다.
TypeScript
// This example uses the Google Maps JavaScript API's Data layer // to create a rectangular polygon with 2 holes in it. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 6, center: { lat: -33.872, lng: 151.252 }, } ); // Define the LatLng coordinates for the outer path. const outerCoords = [ { lat: -32.364, lng: 153.207 }, // north west { lat: -35.364, lng: 153.207 }, // south west { lat: -35.364, lng: 158.207 }, // south east { lat: -32.364, lng: 158.207 }, // north east ]; // Define the LatLng coordinates for an inner path. const innerCoords1 = [ { lat: -33.364, lng: 154.207 }, { lat: -34.364, lng: 154.207 }, { lat: -34.364, lng: 155.207 }, { lat: -33.364, lng: 155.207 }, ]; // Define the LatLng coordinates for another inner path. const innerCoords2 = [ { lat: -33.364, lng: 156.207 }, { lat: -34.364, lng: 156.207 }, { lat: -34.364, lng: 157.207 }, { lat: -33.364, lng: 157.207 }, ]; map.data.add({ geometry: new google.maps.Data.Polygon([ outerCoords, innerCoords1, innerCoords2, ]), }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example uses the Google Maps JavaScript API's Data layer // to create a rectangular polygon with 2 holes in it. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 6, center: { lat: -33.872, lng: 151.252 }, }); // Define the LatLng coordinates for the outer path. const outerCoords = [ { lat: -32.364, lng: 153.207 }, // north west { lat: -35.364, lng: 153.207 }, // south west { lat: -35.364, lng: 158.207 }, // south east { lat: -32.364, lng: 158.207 }, // north east ]; // Define the LatLng coordinates for an inner path. const innerCoords1 = [ { lat: -33.364, lng: 154.207 }, { lat: -34.364, lng: 154.207 }, { lat: -34.364, lng: 155.207 }, { lat: -33.364, lng: 155.207 }, ]; // Define the LatLng coordinates for another inner path. const innerCoords2 = [ { lat: -33.364, lng: 156.207 }, { lat: -34.364, lng: 156.207 }, { lat: -34.364, lng: 157.207 }, { lat: -33.364, lng: 157.207 }, ]; map.data.add({ geometry: new google.maps.Data.Polygon([ outerCoords, innerCoords1, innerCoords2, ]), }); } window.initMap = initMap;
GeoJSON 로드
GeoJSON은 인터넷에서 지리 공간 데이터를 공유하기 위한 공통 표준입니다. 경량형이고 인간이 쉽게 읽을 수 있으므로 공유와 공동작업에 이상적입니다. 데이터 영역을 사용하면 단 한 줄의 코드로 Google 지도에 GeoJSON 데이터를 추가할 수 있습니다.
map.data.loadGeoJson('google.json');
모든 지도에는 GeoJSON을 비롯하여 임의의 지리 공간 데이터의 데이터 영역 역할을 하는 map.data 객체가 있습니다. data 객체의 loadGeoJSON() 메서드를 호출하여 GeoJSON 파일을 로드하고 표시할 수 있습니다. 아래 예는 지도를 추가하고 외부 GeoJSON 데이터를 로드하는 방법을 보여줍니다.
TypeScript
async function initMap() { (await google.maps.importLibrary("maps")) as google.maps.MapsLibrary; const mapElement = document.querySelector( "gmp-map" ) as google.maps.MapElement; let innerMap = mapElement.innerMap; innerMap.data.loadGeoJson("google.json"); } initMap();
JavaScript
async function initMap() { (await google.maps.importLibrary("maps")); const mapElement = document.querySelector("gmp-map"); let innerMap = mapElement.innerMap; innerMap.data.loadGeoJson("google.json"); } initMap();
샘플 사용해 보기
샘플 GeoJSON
이 페이지의 대부분 예에서는 공통 GeoJSON 파일을 사용합니다. 이 파일은 오스트레일리아 위에 다각형으로 'Google'이라는 여섯 개의 문자를 정의합니다. 이 파일을 자유롭게 복사하고 수정하여 데이터 영역을 테스트해 보세요.
참고: 다른 도메인에서 json 파일을 로드하려면 해당 도메인에서 교차 출처 리소스 공유를 사용 설정해야 합니다.
아래에서 'google.json' 옆에 있는 작은 화살표를 확장하면 파일의 전체 텍스트를 볼 수 있습니다.
google.json
{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "letter": "G", "color": "blue", "rank": "7", "ascii": "71" }, "geometry": { "type": "Polygon", "coordinates": [ [ [123.61, -22.14], [122.38, -21.73], [121.06, -21.69], [119.66, -22.22], [119.00, -23.40], [118.65, -24.76], [118.43, -26.07], [118.78, -27.56], [119.22, -28.57], [120.23, -29.49], [121.77, -29.87], [123.57, -29.64], [124.45, -29.03], [124.71, -27.95], [124.80, -26.70], [124.80, -25.60], [123.61, -25.64], [122.56, -25.64], [121.72, -25.72], [121.81, -26.62], [121.86, -26.98], [122.60, -26.90], [123.57, -27.05], [123.57, -27.68], [123.35, -28.18], [122.51, -28.38], [121.77, -28.26], [121.02, -27.91], [120.49, -27.21], [120.14, -26.50], [120.10, -25.64], [120.27, -24.52], [120.67, -23.68], [121.72, -23.32], [122.43, -23.48], [123.04, -24.04], [124.54, -24.28], [124.58, -23.20], [123.61, -22.14] ] ] } }, { "type": "Feature", "properties": { "letter": "o", "color": "red", "rank": "15", "ascii": "111" }, "geometry": { "type": "Polygon", "coordinates": [ [ [128.84, -25.76], [128.18, -25.60], [127.96, -25.52], [127.88, -25.52], [127.70, -25.60], [127.26, -25.79], [126.60, -26.11], [126.16, -26.78], [126.12, -27.68], [126.21, -28.42], [126.69, -29.49], [127.74, -29.80], [128.80, -29.72], [129.41, -29.03], [129.72, -27.95], [129.68, -27.21], [129.33, -26.23], [128.84, -25.76] ], [ [128.45, -27.44], [128.32, -26.94], [127.70, -26.82], [127.35, -27.05], [127.17, -27.80], [127.57, -28.22], [128.10, -28.42], [128.49, -27.80], [128.45, -27.44] ] ] } }, { "type": "Feature", "properties": { "letter": "o", "color": "yellow", "rank": "15", "ascii": "111" }, "geometry": { "type": "Polygon", "coordinates": [ [ [131.87, -25.76], [131.35, -26.07], [130.95, -26.78], [130.82, -27.64], [130.86, -28.53], [131.26, -29.22], [131.92, -29.76], [132.45, -29.87], [133.06, -29.76], [133.72, -29.34], [134.07, -28.80], [134.20, -27.91], [134.07, -27.21], [133.81, -26.31], [133.37, -25.83], [132.71, -25.64], [131.87, -25.76] ], [ [133.15, -27.17], [132.71, -26.86], [132.09, -26.90], [131.74, -27.56], [131.79, -28.26], [132.36, -28.45], [132.93, -28.34], [133.15, -27.76], [133.15, -27.17] ] ] } }, { "type": "Feature", "properties": { "letter": "g", "color": "blue", "rank": "7", "ascii": "103" }, "geometry": { "type": "Polygon", "coordinates": [ [ [138.12, -25.04], [136.84, -25.16], [135.96, -25.36], [135.26, -25.99], [135, -26.90], [135.04, -27.91], [135.26, -28.88], [136.05, -29.45], [137.02, -29.49], [137.81, -29.49], [137.94, -29.99], [137.90, -31.20], [137.85, -32.24], [136.88, -32.69], [136.45, -32.36], [136.27, -31.80], [134.95, -31.84], [135.17, -32.99], [135.52, -33.43], [136.14, -33.76], [137.06, -33.83], [138.12, -33.65], [138.86, -33.21], [139.30, -32.28], [139.30, -31.24], [139.30, -30.14], [139.21, -28.96], [139.17, -28.22], [139.08, -27.41], [139.08, -26.47], [138.99, -25.40], [138.73, -25.00 ], [138.12, -25.04] ], [ [137.50, -26.54], [136.97, -26.47], [136.49, -26.58], [136.31, -27.13], [136.31, -27.72], [136.58, -27.99], [137.50, -28.03], [137.68, -27.68], [137.59, -26.78], [137.50, -26.54] ] ] } }, { "type": "Feature", "properties": { "letter": "l", "color": "green", "rank": "12", "ascii": "108" }, "geometry": { "type": "Polygon", "coordinates": [ [ [140.14,-21.04], [140.31,-29.42], [141.67,-29.49], [141.59,-20.92], [140.14,-21.04] ] ] } }, { "type": "Feature", "properties": { "letter": "e", "color": "red", "rank": "5", "ascii": "101" }, "geometry": { "type": "Polygon", "coordinates": [ [ [144.14, -27.41], [145.67, -27.52], [146.86, -27.09], [146.82, -25.64], [146.25, -25.04], [145.45, -24.68], [144.66, -24.60], [144.09, -24.76], [143.43, -25.08], [142.99, -25.40], [142.64, -26.03], [142.64, -27.05], [142.64, -28.26], [143.30, -29.11], [144.18, -29.57], [145.41, -29.64], [146.46, -29.19], [146.64, -28.72], [146.82, -28.14], [144.84, -28.42], [144.31, -28.26], [144.14, -27.41] ], [ [144.18, -26.39], [144.53, -26.58], [145.19, -26.62], [145.72, -26.35], [145.81, -25.91], [145.41, -25.68], [144.97, -25.68], [144.49, -25.64], [144, -25.99], [144.18, -26.39] ] ] } } ] }
GeoJSON 데이터 스타일 지정
Data.setStyle() 메서드를 사용하여 데이터가 표시되는 방식을 지정합니다. setStyle() 메서드는 StyleOptions 객체 리터럴 또는 각 기능의 스타일을 계산하는 함수 중 하나를 사용합니다.
간단한 스타일 규칙
지형지물의 스타일을 지정하는 가장 간단한 방법은 StyleOptions 객체 리터럴을 setStyle()에 전달하는 것입니다. 이렇게 하면 해당 모음의 각 지형지물에 대해 단일 스타일이 설정됩니다. 각 지형지물 유형은 이용 가능한 옵션의 일부만 렌더링할 수 있습니다. 즉 여러 지형지물 유형의 스타일을 단일 객체 리터럴로 결합할 수 있습니다. 예를 들어 아래 스니펫은 점 도형에만 영향을 미치는 맞춤 icon과 다각형에만 영향을 주는 fillColor를 모두 설정합니다.
map.data.setStyle({ icon: '//example.com/path/to/image.png', fillColor: 'green' });
유효한 스타일/지형지물 조합에 관한 자세한 내용은 스타일 옵션을 참고하세요.
다음은 StyleOptions 객체 리터럴을 사용하여 여러 지형지물의 획 및 채우기 색상을 설정하는 예입니다. 각 다각형의 스타일은 동일하게 지정됩니다.
TypeScript
async function initMap() { (await google.maps.importLibrary("maps")) as google.maps.MapsLibrary; const mapElement = document.querySelector( "gmp-map" ) as google.maps.MapElement; const innerMap = mapElement.innerMap; // Load GeoJSON. google.maps.event.addListenerOnce(innerMap, "idle", () => { innerMap.data.loadGeoJson("google.json"); }); // Set the stroke width, and fill color for each polygon innerMap.data.setStyle({ fillColor: "green", strokeWeight: 1, }); } initMap();
JavaScript
async function initMap() { (await google.maps.importLibrary("maps")); const mapElement = document.querySelector("gmp-map"); const innerMap = mapElement.innerMap; // Load GeoJSON. google.maps.event.addListenerOnce(innerMap, "idle", () => { innerMap.data.loadGeoJson("google.json"); }); // Set the stroke width, and fill color for each polygon innerMap.data.setStyle({ fillColor: "green", strokeWeight: 1, }); } initMap();
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ gmp-map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Data Layer: Styling</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="-28,137" zoom="4"></gmp-map>
</body>
</html>샘플 사용해 보기
선언적 스타일 규칙
마커, 다각형 등 많은 오버레이의 스타일을 업데이트하려면 일반적으로 지도에 각 오버레이를 반복하고 개별적으로 스타일을 설정해야 합니다. 데이터 영역을 사용하면 규칙을 선언적으로 설정할 수 있으며 이 규칙은 전체 데이터 세트에 적용됩니다. 데이터 또는 규칙이 업데이트되면 모든 지형지물에 스타일이 자동으로 적용됩니다. 지형지물 속성을 사용하여 스타일을 맞춤설정할 수 있습니다.
예를 들어 아래 코드는 ASCII 문자 집합에서 문자의 위치를 검사하여 google.json에 있는 각 문자의 색상을 설정합니다. 이 경우에는 데이터와 함께 문자 위치를 인코딩했습니다.
// Color Capital letters blue, and lower case letters red. // Capital letters are represented in ascii by values less than 91 map.data.setStyle(function(feature) { var ascii = feature.getProperty('ascii'); var color = ascii > 91 ? 'red' : 'blue'; return { fillColor: color, strokeWeight: 1 }; });
스타일 삭제
적용된 스타일을 삭제하려면 빈 객체 리터럴을 setStyles() 메서드에 전달하세요.
// Remove custom styles. map.data.setStyle({});
이렇게 하면 지정한 맞춤 스타일이 삭제되고 지형지물이 기본 스타일을 사용하여 렌더링됩니다. 지형지물을 더 이상 렌더링하지 않으려면 StyleOptions의 visible 속성을 false로 설정하세요.
// Hide the Data layer. map.data.setStyle({visible: false});
기본 스타일 재정의
스타일 지정 규칙은 일반적으로 데이터 영역의 모든 지형지물에 적용됩니다. 하지만 특정 지형지물에 특별한 스타일 지정 규칙을 적용하고 싶을 때가 있습니다. 예를 들어 클릭 시 지형지물을 강조표시하기 위함입니다.
특별한 스타일 지정 규칙을 적용하려면 overrideStyle() 메서드를 사용하세요. overrideStyle() 메서드를 사용하여 변경하는 속성은 setStyle()에서 이미 지정된 전체 스타일 외에 추가로 적용됩니다. 예를 들어 아래 코드로 클릭 시 다각형의 채우기 색상이 바뀌지만 다른 스타일이 설정되지는 않습니다.
// Set the global styles. map.data.setStyle({ fillColor: 'green', strokeWeight: 3 }); // Set the fill color to red when the feature is clicked. // Stroke weight remains 3. map.data.addListener('click', function(event) { map.data.overrideStyle(event.feature, {fillColor: 'red'}); });
revertStyle() 메서드를 호출하여 모든 스타일 재정의를 삭제합니다.
스타일 옵션
각 지형지물의 스타일 지정에 사용할 수 있는 옵션은 지형지물 유형에 따라 달라집니다.
예를 들어 fillColor는 다각형 도형에서만, icon은 점 도형에서만 표시됩니다. 자세한 내용은 StyleOptions 참조 문서를 확인하세요.
모든 도형에서 사용 가능한 옵션
clickable:true인 경우 지형지물에서 마우스 및 터치 이벤트를 수신합니다.visible:true인 경우 지형지물이 표시됩니다.zIndex: 모든 지형지물이zIndex순으로 지도에 표시되며 값이 더 큰 지형지물이 값이 더 작은 지형지물 앞에 표시됩니다. 마커는 항상 선 문자열과 다각형 앞에 표시됩니다.
점 도형에 사용 가능한 옵션
cursor: 마우스 오버 시 표시되는 마우스 커서icon: 점 도형에 대해 표시되는 아이콘shape: 조회 감지에 사용되는 이미지 지도 정의title: 마우스 오버 텍스트
선 도형에 사용 가능한 옵션
strokeColor: 획 색상 확장된 이름이 지정된 색상을 제외하고 모든 CSS3 색상이 지원됩니다.strokeOpacity: 획 불투명도(0.0~1.0)strokeWeight: 획 너비(픽셀)
다각형 도형에서 사용 가능한 옵션
fillColor: 채우기 색상 확장된 이름이 지정된 색상을 제외하고 모든 CSS3 색상이 지원됩니다.fillOpacity: 채우기 불투명도(0.0~1.0.)strokeColor: 획 색상 확장된 이름이 지정된 색상을 제외하고 모든 CSS3 색상이 지원됩니다.strokeOpacity: 획 불투명도(0.0~1.0)strokeWeight: 획 너비(픽셀)
이벤트 핸들러 추가
지형지물은 mouseup 또는 mousedown과 같은 이벤트에 응답합니다. 이벤트 리스너를 추가하여 사용자가 지도의 데이터와 상호작용하도록 할 수 있습니다. 아래 예에서는 마우스 커서 아래에 지형지물에 대한 정보를 표시하는 마우스 오버 이벤트를 추가합니다.
// Set mouseover event for each feature. map.data.addListener('mouseover', function(event) { document.getElementById('info-box').textContent = event.feature.getProperty('letter'); });
데이터 영역 이벤트
다음 이벤트는 도형 유형에 관계없이 모든 지형지물에 공통된 이벤트입니다.
addfeatureclickdblclickmousedownmouseoutmouseovermouseupremovefeatureremovepropertyrightclicksetgeometrysetproperty
이러한 이벤트에 대한 자세한 내용은 google.maps.data 클래스의 참조 문서에서 확인할 수 있습니다.
동적으로 모양 변경
각 지형지물의 스타일을 계산하는 함수를 google.maps.data.setStyle() 메서드에 전달하여 데이터 영역의 스타일을 설정할 수 있습니다. 이 함수는 지형지물의 속성이 업데이트될 때마다 호출됩니다.
아래 예는 지형지물의 isColorful 속성을 업데이트하는 click 이벤트에 대한 이벤트 리스너를 추가합니다. 지형지물의 스타일 지정은 속성이 설정되는 즉시 변경사항을 반영하여 업데이트됩니다.
// Color each letter gray. Change the color when the isColorful property // is set to true. map.data.setStyle(function(feature) { var color = 'gray'; if (feature.getProperty('isColorful')) { color = feature.getProperty('color'); } return /** @type {!google.maps.Data.StyleOptions} */({ fillColor: color, strokeColor: color, strokeWeight: 2 }); }); // When the user clicks, set 'isColorful', changing the color of the letters. map.data.addListener('click', function(event) { event.feature.setProperty('isColorful', true); }); // When the user hovers, tempt them to click by outlining the letters. // Call revertStyle() to remove all overrides. This will use the style rules // defined in the function passed to setStyle() map.data.addListener('mouseover', function(event) { map.data.revertStyle(); map.data.overrideStyle(event.feature, {strokeWeight: 8}); }); map.data.addListener('mouseout', function(event) { map.data.revertStyle(); });