Визуализация данных: картирование землетрясений

Обзор

В этом руководстве показано, как визуализировать данные на картах Google. Например, карты в этом руководстве визуализируют данные о местоположении землетрясений и их магнитуде. Изучите методы работы с собственными источниками данных и создавайте впечатляющие истории на картах Google, подобные представленным ниже.

Первые два кадра выше (слева направо) отображают карты с базовыми маркерами и кругами заданного размера . Последний кадр отображает тепловую карту .

Импортируйте ваши данные

В этом руководстве используются данные о землетрясениях в режиме реального времени, предоставленные Геологической службой США (USGS). Сайт USGS предоставляет данные в различных форматах, которые вы можете скопировать на свой домен для локального доступа через приложение. В этом руководстве JSONP-файлы запрашиваются непосредственно с серверов USGS, добавляя тег script в заголовок документа.

// Create a script tag and set the USGS URL as the source.         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);

Разместите основные маркеры

Теперь, когда вы загрузили данные о местах землетрясений из Геологической службы США (USGS) в своё приложение, вы можете отобразить их на карте. В этом разделе показано, как создать карту, которая использует импортированные данные для размещения базового маркера в эпицентре каждого землетрясения.

В разделе ниже представлен весь код, необходимый для создания карты в этом руководстве.

Машинопись

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

Попробуйте образец

Используйте фигуры и тепловые карты для настройки карт

В этом разделе показаны другие способы настройки расширенных наборов данных на карте. Рассмотрим карту, созданную в предыдущем разделе этого руководства, на которой маркеры отмечены для каждого места землетрясения. Вы можете настроить маркеры для визуализации дополнительных данных, например, мест наибольшего количества землетрясений, их магнитуды или глубины.

Вот несколько вариантов настройки базового маркера:

  • Используя размер круга :
    Вы можете рисовать круги (или любые другие фигуры) с размерами, соответствующими магнитуде землетрясения, используя символы . Таким образом, сильные землетрясения будут представлены на карте в виде самых больших кругов.

  • Использование тепловых карт :
    Слой «Тепловая карта» в библиотеке визуализации предлагает простой, но мощный способ отображения распределения землетрясений. Тепловые карты используют цвета для отображения плотности точек, что упрощает выделение областей с высокой активностью. Тепловые карты также могут использовать WeightedLocations , чтобы, например, более заметные землетрясения были видны на тепловой карте.

Размер круга

На карте ниже маркеры отображаются в виде кругов. Размер круга увеличивается с увеличением магнитуды землетрясения в данном месте.

В разделе ниже представлен весь код, необходимый для создания карты с настраиваемыми круглыми маркерами.

Машинопись

let map: google.maps.Map;  function initMap(): void {   map = new google.maps.Map(document.getElementById("map") as HTMLElement, {     zoom: 2,     center: { lat: -33.865427, lng: 151.196123 },     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);    map.data.setStyle((feature) => {     const magnitude = feature.getProperty("mag") as number;     return {       icon: getCircle(magnitude),     };   }); }  function getCircle(magnitude: number) {   return {     path: google.maps.SymbolPath.CIRCLE,     fillColor: "red",     fillOpacity: 0.2,     scale: Math.pow(2, magnitude) / 2,     strokeColor: "white",     strokeWeight: 0.5,   }; }  function eqfeed_callback(results: any) {   map.data.addGeoJson(results); }  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: { lat: -33.865427, lng: 151.196123 },     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);   map.data.setStyle((feature) => {     const magnitude = feature.getProperty("mag");     return {       icon: getCircle(magnitude),     };   }); }  function getCircle(magnitude) {   return {     path: google.maps.SymbolPath.CIRCLE,     fillColor: "red",     fillOpacity: 0.2,     scale: Math.pow(2, magnitude) / 2,     strokeColor: "white",     strokeWeight: 0.5,   }; }  function eqfeed_callback(results) {   map.data.addGeoJson(results); }  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 Circles</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>

Попробуйте образец

Тепловые карты

Тепловые карты упрощают понимание распределения землетрясений, зафиксированных Геологической службой США (USGS). Вместо маркера на каждом эпицентре тепловые карты используют цвет и форму для представления распределения данных. В этом примере красный цвет обозначает области высокой сейсмической активности.

В разделе ниже представлен весь код, необходимый для создания этой карты.

Машинопись

let map: google.maps.Map;  function initMap(): void {   map = new google.maps.Map(document.getElementById("map") as HTMLElement, {     zoom: 2,     center: { lat: -33.865427, lng: 151.196123 },     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); }  function eqfeed_callback(results: any) {   const heatmapData: google.maps.LatLng[] = [];    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]);      heatmapData.push(latLng);   }    const heatmap = new google.maps.visualization.HeatmapLayer({     data: heatmapData,     dissipating: false,     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: { lat: -33.865427, lng: 151.196123 },     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); }  function eqfeed_callback(results) {   const heatmapData = [];    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]);      heatmapData.push(latLng);   }    const heatmap = new google.maps.visualization.HeatmapLayer({     data: heatmapData,     dissipating: false,     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 Heatmap</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&libraries=visualization&v=weekly"       defer     ></script>   </body> </html>

Попробуйте образец

Дополнительная информация

Узнайте больше по следующим темам: