개요
로컬 또는 원격 소스에서 GeoJSON 데이터를 가져와 지도에 표시하는 방법을 알아보세요. 이 튜토리얼에서는 아래 지도를 사용하여 지도로 데이터를 가져오는 다양한 기법을 설명합니다.
아래 섹션에는 이 튜토리얼에서 지도를 만드는 데 필요한 전체 코드가 표시되어 있습니다.
let map: google.maps.Map; function initMap(): void { map = new google.maps.Map(document.getElementById("map") as HTMLElement, { zoom: 2, center: new google.maps.LatLng(2.8, -187.3), mapTypeId: "terrain", }); // Create a <script> tag and set the USGS URL as the source. const script = document.createElement("script"); // This example uses a local copy of the GeoJSON stored at // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp script.src = "https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js"; document.getElementsByTagName("head")[0].appendChild(script); } // Loop through the results array and place a marker for each // set of coordinates. const eqfeed_callback = function (results: any) { for (let i = 0; i < results.features.length; i++) { const coords = results.features[i].geometry.coordinates; const latLng = new google.maps.LatLng(coords[1], coords[0]); new google.maps.Marker({ position: latLng, map: map, }); } }; declare global { interface Window { initMap: () => void; eqfeed_callback: (results: any) => void; } } window.initMap = initMap; window.eqfeed_callback = eqfeed_callback;
let map; function initMap() { map = new google.maps.Map(document.getElementById("map"), { zoom: 2, center: new google.maps.LatLng(2.8, -187.3), mapTypeId: "terrain", }); // Create a <script> tag and set the USGS URL as the source. const script = document.createElement("script"); // This example uses a local copy of the GeoJSON stored at // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp script.src = "https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js"; document.getElementsByTagName("head")[0].appendChild(script); } // Loop through the results array and place a marker for each // set of coordinates. const eqfeed_callback = function (results) { for (let i = 0; i < results.features.length; i++) { const coords = results.features[i].geometry.coordinates; const latLng = new google.maps.LatLng(coords[1], coords[0]); new google.maps.Marker({ position: latLng, map: map, }); } }; window.initMap = initMap; window.eqfeed_callback = eqfeed_callback;
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ #map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
<html> <head> <title>Earthquake Markers</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <div id="map"></div> <!-- The `defer` attribute causes the script to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises. See https://developers.google.com/maps/documentation/javascript/load-maps-js-api for more information. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly" defer ></script> </body> </html>
샘플 사용해 보기
데이터 로드
이 섹션에서는 Maps JavaScript API 애플리케이션과 동일한 도메인 또는 다른 도메인에서 데이터를 로드하는 방법을 설명합니다.
동일한 도메인에서 데이터 로드
Google 지도 데이터 레이어는 임의의 지리 공간 데이터(GeoJSON 포함)를 위한 컨테이너를 제공합니다. 데이터가 Maps JavaScript API 애플리케이션과 동일한 도메인에 호스팅된 파일에 들어 있는 경우 map.data.loadGeoJson()
메서드를 사용하여 데이터를 로드할 수 있습니다. 파일은 동일한 도메인에 있어야 하지만 다른 하위 도메인에서 호스팅해도 됩니다. 예를 들어 www.example.com에서 files.example.com으로 요청을 전송할 수 있습니다.
map.data.loadGeoJson('data.json');
다른 도메인에서 데이터 로드
자체 도메인이 아닌 다른 도메인에 요청을 전송할 수 있도록 도메인이 구성된 경우, 다른 도메인의 데이터를 요청할 수도 있습니다. 이 권한에 대한 표준을 교차 출처 리소스 공유(CORS)라고 합니다. 도메인에서 교차 도메인 요청을 허용하는 경우 응답 헤더에 다음 선언을 포함해야 합니다.
Access-Control-Allow-Origin: *
Chrome 개발자 도구(DevTools)를 사용하여 도메인에 CORS가 사용 설정되어 있는지 확인합니다.
이러한 도메인에서는 동일한 도메인에서 JSON을 로드하는 것과 마찬가지로 데이터를 로드하면 됩니다.
map.data.loadGeoJson('http://www.CORS-ENABLED-SITE.com/data.json');
JSONP 요청
이 기법을 사용하려면 대상 도메인에서 JSONP 요청을 지원해야 합니다.
JSONP를 요청하려면 createElement()
를 사용하여 script
태그를 문서 헤드에 추가하세요.
var script = document.createElement('script');
script.src = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp';
document.getElementsByTagName('head')[0].appendChild(script);
스크립트가 실행되면 대상 도메인에서 일반적으로 callback()
이라고 하는 다른 스크립트에 데이터를 인수로 전달합니다. 대상 도메인은 브라우저에서 대상 URL을 로드할 때 페이지에 맨 먼저 표시되는 이름인 콜백 스크립트 이름을 정의합니다.
예를 들어 브라우저 창에 http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp를 로드하면 콜백 이름이 eqfeed_callback
이라고 표시됩니다.
코드에 콜백 스크립트를 정의해야 합니다.
function eqfeed_callback(response) {
map.data.addGeoJson(response);
}
addGeoJson()
메서드를 사용하여 파싱된 GeoJSON 데이터를 지도에 배치합니다.
데이터 스타일 지정
GeoJSON 데이터를 지도 객체에 추가하여 데이터의 모양을 변경할 수 있습니다. 데이터 스타일 지정에 관한 자세한 내용은 개발자 가이드를 참고하세요.
자세히 알아보기
- GeoJSON은 JSON(JavaScript 객체 표기법)을 기반으로 지리 데이터를 인코딩하는 데 널리 사용되는 개방형 형식입니다. JSON 데이터용으로 설계된 JavaScript 도구 및 메서드를 GeoJSON과도 함께 사용할 수 있습니다. 자세한 내용은 개발자 가이드를 참고하세요.
- JSONP는 패딩된 JSON을 의미합니다. 이는 웹브라우저에서 실행되는 JavaScript 프로그램에서 다른 도메인의 서버에 데이터를 요청하기 위해 사용하는 통신 방법입니다.