Nhập dữ liệu 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 nguồn từ xa rồi hiển thị dữ liệu đó trên bản đồ của bạn. Hướng dẫn này sử dụng bản đồ dưới đây để minh hoạ các kỹ thuật nhập dữ liệu vào bản đồ.

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

TypeScript

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;

JavaScript

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;

CSS

/* 
 * 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

<html>
  <head>
    <title>Earthquake Markers</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <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 callback 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 cho bạn biết cách tải dữ liệu từ cùng một miền như ứng dụng Maps JavaScript API của bạn 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, bạn có thể tải tệp đó bằng phương thức map.data.loadGeoJson(). Tệp phải ở 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ể tạo yêu cầu tới files.example.com từ www.example.com.

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

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

Bạn cũng có thể yêu cầu dữ liệu từ một miền không phải của bạn, 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 gọi là Chia sẻ tài nguyên nhiều nguồn gốc (CORS). Nếu một miền đã cho phép 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 đã bật CORS hay chưa.

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

Đang yêu cầu JSONP

Miền mục tiêu phải hỗ trợ các yêu cầu cho 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 phần đầu của 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 một đối số cho tập lệnh khác, thường có tên là callback(). Miền mục tiêu xác định tên tập lệnh gọi lại, 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 dưới dạng eqfeed_callback.

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

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 đồ.

Tạo 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 Maps. Hãy đọc hướng dẫn của nhà phát triển để biết thêm thông tin về cách tạo 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 có đệm. Đây là một phương thức liên lạc 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.