يمكنك إضافة خريطة Google إلى صفحة ويب باستخدام رمز HTML وCSS وJavaScript. توضّح هذه الصفحة كيفية إضافة خريطة إلى صفحة ويب، ثم الوصول إلى مثيل الخريطة آليًا.
- إضافة خريطة باستخدام عنصر
gmp-map - إضافة خريطة باستخدام عنصر
divوJavaScript - ضبط الخصائص والحصول عليها في مثيل الخريطة
نظرة عامة
لتحميل خريطة، يجب أن تنفّذ صفحة الويب الإجراءات التالية:
- تحميل Maps JavaScript API باستخدام عامل التحميل التمهيدي. هذا هو المكان الذي يتم فيه تمرير مفتاح واجهة برمجة التطبيقات. ويمكن إضافته إلى ملفات مصدر HTML أو JavaScript.
- إضافة الخريطة إلى صفحة HTML وإضافة أنماط CSS اللازمة
- تحميل مكتبة
mapsوتهيئة الخريطة
إضافة خريطة باستخدام عنصر gmp-map
يُعدّ عنصر gmp-map الطريقة المفضّلة لإضافة خريطة Google إلى صفحة ويب.
وهو عنصر HTML مخصّص تم إنشاؤه باستخدام مكوّنات الويب. لإضافة خريطة إلى صفحة ويب باستخدام عنصر gmp-map، اتّبِع الخطوات التالية.
أضِف عنصر
scriptيحتوي على أداة bootstrap إلى صفحة HTML، أو أضِفه إلى ملف مصدر JavaScript أو TypeScript بدون عنصرscript. اضبط أداة bootstrap باستخدام مفتاح واجهة برمجة التطبيقات وأي خيارات أخرى. يمكنك اختيار استيراد المكتبة ديناميكيًا أو تحميل النص البرمجي مباشرةً. يعرض هذا المثال إضافة أداة bootstrap لتحميل النص البرمجي ديناميكيًا إلى صفحة HTML:<script> (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({ key: "YOUR_API_KEY", v: "weekly", // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.). // Add other bootstrap parameters as needed, using camel case. }); </script>
في صفحة HTML، أضِف عنصر
gmp-map. حدِّد إحداثيات خط العرض وخط الطول لـcenter(مطلوبة)، وقيمة التكبير/التصغير لـzoom(مطلوبة)، وmap-idإذا لزم الأمر (مطلوبة لبعض الميزات، مثل "العلامات المتقدّمة").
<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID"> </gmp-map>
مثال على الشفرة الكاملة
TypeScript
async function init(): Promise<void> { // Import the needed libraries. await google.maps.importLibrary('maps'); // Access the map. const mapElement = document.querySelector('gmp-map')!; // Access the underlying map object. const innerMap = mapElement.innerMap; console.log({ mapElement, innerMap }); } void init();
JavaScript
async function init() { // Import the needed libraries. await google.maps.importLibrary('maps'); // Access the map. const mapElement = document.querySelector('gmp-map'); // Access the underlying map object. const innerMap = mapElement.innerMap; console.log({ mapElement, innerMap }); } void init();
CSS
/* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Simple Map</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<script>
// prettier-ignore
(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8"
});
</script>
</head>
<body>
<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID">
</gmp-map>
</body>
</html>تجربة نموذج
إضافة خريطة باستخدام عنصر div وJavaScript
لإضافة خريطة إلى صفحة ويب باستخدام عنصر div، اتّبِع الخطوات التالية.
أضِف عنصر
scriptيحتوي على أداة bootstrap إلى صفحة HTML، أو أضِفه إلى ملف مصدر JavaScript أو TypeScript بدون عنصرscript. اضبط أداة bootstrap باستخدام مفتاح واجهة برمجة التطبيقات وأي خيارات أخرى. يمكنك اختيار استيراد المكتبة ديناميكيًا أو تحميل النص البرمجي مباشرةً. يعرض هذا المثال إضافة أداة bootstrap الديناميكية إلى صفحة HTML:<script> (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({ key: "YOUR_API_KEY", v: "weekly", // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.). // Add other bootstrap parameters as needed, using camel case. }); </script>
في صفحة HTML، أضِف عنصر
divليحتوي على الخريطة.<div id="map"></div>
في CSS، اضبط ارتفاع الخريطة على %100. سمة CSS
heightمطلوبة لكي تظهر الخريطة.#map { height: 100%; }
في ملف JS أو TS، أنشِئ دالة لتحميل مكتبة
mapsوتهيئة الخريطة. حدِّد إحداثيات خط العرض وخط الطول لـcenter، ومستوى التكبير/التصغير الذي سيتم استخدامه لـzoom. إذا لزم الأمر، أضِف معرّف خريطة باستخدام السمةmapId. بما أنّ الخريطة ستكون تلقائيًا خريطة نقطية، اطلب خريطة متّجهة من خلال تحديد خيار الخريطة "VECTOR". ننصح باستخدام نوع الخريطة المتّجهة للحصول على أفضل تجربة مستخدم، لأنّها توفّر دقة بصرية محسّنة بالإضافة إلى إمكانية التحكّم في الميل والاتجاه على الخريطة.TypeScript
let map: google.maps.Map; async function init(): Promise<void> { // Import the needed libraries const { Map } = await google.maps.importLibrary('maps'); // Create a new map from the div with id="map". map = new Map(document.getElementById('map')!, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: 'VECTOR', }); console.log(map); } void init();
JavaScript
let map; async function init() { // Import the needed libraries const { Map } = await google.maps.importLibrary('maps'); // Create a new map from the div with id="map". map = new Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: 'VECTOR', }); console.log(map); } void init();
الاطّلاع على رمز المصدر الكامل للمثال
TypeScript
let map: google.maps.Map; async function init(): Promise<void> { // Import the needed libraries const { Map } = await google.maps.importLibrary('maps'); // Create a new map from the div with id="map". map = new Map(document.getElementById('map')!, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: 'VECTOR', }); console.log(map); } void init();
JavaScript
let map; async function init() { // Import the needed libraries const { Map } = await google.maps.importLibrary('maps'); // Create a new map from the div with id="map". map = new Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: 'VECTOR', }); console.log(map); } void init();
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>Simple Map</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<script>
// prettier-ignore
(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8"
});
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>تجربة نموذج
ضبط الخصائص والحصول عليها في مثيل الخريطة
للتفاعل مع مثيل الخريطة، اختَر العنصر الذي يحتوي عليها. سيختلف الرمز البرمجي الذي يتم استخدامه وفقًا لما إذا كنت قد استخدَمت عنصر gmp-map أو عنصر div.
الحصول على مثيل خريطة من عنصر gmp-map
للحصول على مثيل الخريطة عند استخدام عنصر gmp-map، استخدِم
document.querySelector لاسترداد مثيل mapElement
، كما هو موضّح هنا.
const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
بعد ذلك، اضبط الخصائص في مثيل mapElement:
mapElement.zoom = 8;
يستخدم الصف MapElement الصف Map داخليًا. يمكنك الوصول إلى الصف Map
باستخدام السمة MapElement.innerMap، كما هو موضّح هنا:
mapElement.innerMap.setOptions({
mapTypeControl: false,
});
الحصول على مثيل خريطة من عنصر div
عند استخدام عنصر div، احصل على مثيل الخريطة واضبط الخيارات في وقت التهيئة:
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
mapTypeControl: false,
});
بعد التهيئة، اضبط الخيارات في مثيل map كما هو موضّح هنا:
map.setOptions({
zoom: 8,
});