استيراد بيانات GeoJSON إلى "خرائط Google"

نظرة عامة

تعلَّف على كيفية استيراد بيانات GeoJSON من مصدر محلي أو بعيد وعرضها على خريطتك. يستخدِم هذا البرنامج التعليمي الخريطة أدناه لتوضيح تقنيات مختلفة لاستيراد البيانات إلى الخرائط.

يعرض القسم أدناه الرمز البرمجي الكامل الذي تحتاج إليه لإنشاء الخريطة في هذا البرنامج التعليمي.

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>

    <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(). يجب أن يكون الملف على النطاق نفسه، ولكن يمكنك استضافته في نطاق فرعي مختلف. على سبيل المثال، يمكنك إرسال طلب إلى files.example.com من www.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 إلى عنصر Map. يُرجى قراءة دليل المطوّرين لمزيد من المعلومات حول تنسيق بياناتك.

مزيد من المعلومات

  • ‫GeoJSON هو تنسيق مفتوح شائع الاستخدام لترميز البيانات الجغرافية، استنادًا إلى JSON (JavaScript Object Notation). تعمل أيضًا أدوات JavaScript والطرق المصمّمة لبيانات JSON مع GeoJSON. يُرجى قراءة دليل المطوّرين لمزيد من المعلومات.
  • ‫JSONP هو اختصار لـ JSON padded. وهي طريقة تواصل تُستخدم في برامج JavaScript التي تعمل في متصفّحات الويب لطلب بيانات من خادم في نطاق مختلف.