סקירה כללית
איך מייבאים נתוני 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: *
כדי לבדוק אם הופעל CORS בדומיין, אפשר להשתמש בכלים למפתחים ב-Chrome.

טעינת נתונים מדומיין כזה זהה לטעינת 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(). דומיין היעד מגדיר את שם הסקריפט של הקריאה החוזרת (callback), שהוא השם הראשון בדף כשאתם טוענים את כתובת ה-URL של היעד בדפדפן.
לדוגמה, טוענים את הכתובת http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp בחלון הדפדפן כדי לחשוף את שם הקריאה החוזרת בתור eqfeed_callback.

צריך להגדיר את הסקריפט של פונקציית ה-callback בקוד:
function eqfeed_callback(response) {
map.data.addGeoJson(response);
}
משתמשים ב-method addGeoJson() כדי להציב את נתוני ה-GeoJSON המנותחים במפה.
ייבוא אובייקטים גיאומטריים של GeoJSON
ה-method map.data.addGeoJson() דורשת אובייקט Feature או FeatureCollection מסוג GeoJSON שעבר ניתוח. היא לא מקבלת ישירות אובייקטים גיאומטריים עצמאיים של GeoJSON (Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon או GeometryCollection).
אם מקור הנתונים או התגובה מה-API מחזירים אובייקט גיאומטרי עצמאי של GeoJSON בלי wrapper ברמה העליונה של "type": "Feature", צריך לעטוף אותו באובייקט Feature לפני שקוראים ל-map.data.addGeoJson().
לדוגמה, אם הגיאומטריה (כמו Polygon) היא אובייקט JavaScript מנותח, צריך לעטוף אותה באובייקט Feature:
const polygonGeometry = {
type: "Polygon",
coordinates: [
[
[-78.45, 35.82],
[-78.41, 35.73],
[-78.28, 35.66],
[-78.45, 35.82],
],
],
};
const geoJsonFeature = {
type: "Feature",
geometry: polygonGeometry,
};
map.data.addGeoJson(geoJsonFeature);
אם הגיאומטריה מוחזרת כמחרוזת בפורמט JSON (לדוגמה, השדה polygon שמוחזר על ידי התראת מזג אוויר או תגובת גבול), אפשר גם להוסיף כותרת עליונה בתחילת המחרוזת וכותרת תחתונה בסוף המחרוזת כדי ליצור Feature תקין של GeoJSON לפני הניתוח שלו באמצעות JSON.parse():
const geojson_header = "{\"type\":\"Feature\", \"geometry\": ";
const geojson_footer = "}";
map.data.addGeoJson(
JSON.parse(geojson_header + polygon + geojson_footer));
מידע נוסף על עבודה עם גיאומטריות ופוליגונים בשכבת הנתונים זמין במדריך למפתחים בנושא שכבת הנתונים.
עיצוב הנתונים
כדי לשנות את המראה של הנתונים, אתם יכולים להוסיף נתוני GeoJSON לאובייקט Map. מידע נוסף על עיצוב הנתונים זמין במדריך למפתחים.
מידע נוסף
- GeoJSON הוא פורמט פתוח נפוץ לקידוד נתונים גיאוגרפיים, שמבוסס על JSON (JavaScript Object Notation). כלים ושיטות של JavaScript שמיועדים לנתוני JSON פועלים גם עם GeoJSON. מידע נוסף זמין במדריך למפתחים.
- JSONP הוא ראשי תיבות של padded JSON (ריפוד JSON). זו שיטת תקשורת שמשתמשים בה בתוכנות JavaScript שפועלות בדפדפני אינטרנט, כדי לבקש נתונים משרת בדומיין אחר.