Nhập dữ liệu GeoJSON vào Maps

Tổng quan

Tìm hiểu cách nhập dữ liệu GeoJSON từ nguồn cục bộ hoặc từ xa và hiển thị dữ liệu đó trên bản đồ. Bài viết này sử dụng bản đồ dưới đây để minh hoạ nhiều kỹ thuật nhập dữ liệu vào bản đồ.

Phần bên dưới hiển thị toàn bộ mã bạn cần để tạo bản đồ trong hướng dẫn này.

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>

Thử mẫu

Đang tải dữ liệu

Phần này hướng dẫn bạn cách tải dữ liệu từ cùng một miền với ứng dụng API Maps JavaScript hoặc từ một miền khác.

Tải dữ liệu từ cùng một miền

Lớp dữ liệu của Google Maps cung cấp một vùng chứa cho dữ liệu không gian địa lý tuỳ ý (bao gồm cả GeoJSON). Nếu dữ liệu của bạn nằm trong một tệp được lưu trữ trên cùng một miền với ứng dụng API JavaScript của Maps, thì bạn có thể tải dữ liệu đó bằng phương thức map.data.loadGeoJson(). Tệp phải nằm trên cùng một miền, nhưng bạn có thể lưu trữ tệp đó trong một miền con khác. Ví dụ: bạn có thể gửi yêu cầu đến files.example.com từ www.example.com.

map.data.loadGeoJson('data.json');

Tải dữ liệu trên các miền

Bạn cũng có thể yêu cầu dữ liệu từ một miền khác với miền của mình, nếu cấu hình của miền cho phép yêu cầu như vậy. Tiêu chuẩn cho quyền này được gọi là Chia sẻ tài nguyên trên nhiều nguồn gốc (CORS). Nếu một miền đã cho phép các yêu cầu trên nhiều miền, thì tiêu đề phản hồi của miền đó phải bao gồm nội dung khai báo sau:

Access-Control-Allow-Origin: *

Sử dụng Công cụ cho nhà phát triển Chrome (DevTools) để tìm hiểu xem một miền có bật CORS hay không.

Việc tải dữ liệu từ một miền như vậy cũng giống như việc tải JSON từ cùng một miền:

map.data.loadGeoJson('http://www.CORS-ENABLED-SITE.com/data.json');

Yêu cầu JSONP

Miền mục tiêu phải hỗ trợ các yêu cầu về JSONP để sử dụng kỹ thuật này.

Để yêu cầu JSONP, hãy sử dụng createElement() để thêm thẻ script vào đầu tài liệu.

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

Khi tập lệnh chạy, miền mục tiêu sẽ truyền dữ liệu dưới dạng đối số đến một tập lệnh khác, thường được đặt tên là callback(). Miền mục tiêu xác định tên tập lệnh gọi lại, đây là tên đầu tiên trên trang khi bạn tải URL mục tiêu trong trình duyệt.

Ví dụ: tải http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp trong cửa sổ trình duyệt để hiển thị tên lệnh gọi lại là eqfeed_callback.

Bạn phải xác định tập lệnh gọi lại trong mã:

function eqfeed_callback(response) {
  map.data.addGeoJson(response);
}

Sử dụng phương thức addGeoJson() để đặt dữ liệu GeoJSON đã phân tích cú pháp trên bản đồ.

Định kiểu dữ liệu

Bạn có thể thay đổi giao diện của dữ liệu bằng cách thêm dữ liệu GeoJSON vào đối tượng Bản đồ. Hãy đọc hướng dẫn dành cho nhà phát triển để biết thêm thông tin về cách thiết lập kiểu cho dữ liệu.

Tìm hiểu thêm

  • GeoJSON là một định dạng mở được sử dụng rộng rãi để mã hoá dữ liệu địa lý, dựa trên JSON (Ký hiệu đối tượng JavaScript). Các công cụ và phương thức JavaScript được thiết kế cho dữ liệu JSON cũng hoạt động với GeoJSON. Hãy đọc hướng dẫn dành cho nhà phát triển để biết thêm thông tin.
  • JSONP là viết tắt của JSON đã đệm. Đây là một phương thức giao tiếp được sử dụng trong các chương trình JavaScript chạy trong trình duyệt web để yêu cầu dữ liệu từ một máy chủ trong một miền khác.