إضافة "خرائط Google" إلى صفحة ويب

يمكنك إضافة خريطة Google إلى صفحة ويب باستخدام رموز HTML وCSS وJavaScript. توضّح هذه الصفحة كيفية إضافة خريطة إلى صفحة ويب، ثم الوصول إلى مثيل الخريطة آليًا.

نظرة عامة

لتحميل خريطة، يجب أن تنفّذ صفحة الويب الإجراءات التالية:

  • حمِّل Maps JavaScript API باستخدام أداة تحميل bootstrap. هذا هو المكان الذي يتم فيه تمرير مفتاح واجهة برمجة التطبيقات. ويمكن إضافتها إلى ملفات المصدر الخاصة بلغة HTML أو JavaScript.
  • أضِف الخريطة إلى صفحة HTML، وأضِف أنماط CSS اللازمة.
  • حمِّل مكتبة maps وأعِد ضبط الخريطة.

إضافة خريطة باستخدام عنصر gmp-map

يُعدّ العنصر gmp-map الطريقة المفضّلة لإضافة خريطة Google إلى صفحة ويب. وهو عنصر HTML مخصّص تم إنشاؤه باستخدام مكوّنات الويب. لإضافة خريطة إلى صفحة ويب باستخدام عنصر gmp-map، اتّبِع الخطوات التالية.

  1. أضِف عنصر script يحتوي على برنامج الإعداد إلى صفحة HTML، أو أضِفه إلى ملف مصدر JavaScript أو TypeScript بدون عنصر script. اضبط عملية الإعداد باستخدام مفتاح واجهة برمجة التطبيقات وأي خيارات أخرى. يمكنك اختيار إما استيراد المكتبة الديناميكية أو تحميل البرنامج النصي مباشرةً. يوضّح هذا المثال كيفية إضافة برنامج التحميل التمهيدي لتحميل النصوص البرمجية الديناميكية إلى صفحة 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>

    مزيد من المعلومات حول تحميل Google Maps JavaScript API

  2. في صفحة HTML، أضِف عنصر gmp-map. حدِّد إحداثيات خطوط الطول والعرض الخاصة بالسمة center (مطلوبة)، وقيمة التكبير/التصغير الخاصة بالسمة zoom (مطلوبة)، والسمة map-id إذا لزم الأمر (مطلوبة لبعض الميزات، مثل &quot;العلامات المتقدّمة&quot;).

<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID">
</gmp-map>

مثال على الرمز البرمجي الكامل

TypeScript

async function initMap(): Promise<void> {
    // Import the needed libraries.
    await google.maps.importLibrary('maps');

    // Create the map.
    const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
    // Access the underlying map object.
    const innerMap = mapElement.innerMap;
}

initMap();

JavaScript

async function initMap() {
    // Import the needed libraries.
    await google.maps.importLibrary('maps');
    // Create the map.
    const mapElement = document.querySelector('gmp-map');
    // Access the underlying map object.
    const innerMap = mapElement.innerMap;
}
initMap();

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>
        <!-- prettier-ignore -->
        <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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly" });</script>
    </head>

    <body>
        <gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID">
        </gmp-map>
    </body>
</html>

تجربة عيّنة

إضافة خريطة باستخدام عنصر div وJavaScript

لإضافة خريطة إلى صفحة ويب باستخدام عنصر div، اتّبِع الخطوات التالية.

  1. أضِف عنصر script يحتوي على برنامج الإعداد إلى صفحة HTML، أو أضِفه إلى ملف مصدر JavaScript أو TypeScript بدون عنصر script. اضبط عملية الإعداد باستخدام مفتاح واجهة برمجة التطبيقات وأي خيارات أخرى. يمكنك اختيار إما استيراد المكتبة الديناميكية أو تحميل البرنامج النصي مباشرةً. يوضّح المثال التالي كيفية إضافة عملية الإعداد الديناميكي إلى صفحة 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>

    مزيد من المعلومات حول تحميل Google Maps JavaScript API

  2. في صفحة HTML، أضِف عنصر div لاحتواء الخريطة.

    <div id="map"></div>
  3. في CSS، اضبط ارتفاع الخريطة على %100. سمة height في CSS مطلوبة لكي تكون الخريطة مرئية.

    #map {
      height: 100%;
    }
  4. في ملف JS أو TS، أنشئ دالة لتحميل مكتبة maps وتهيئة الخريطة. حدِّد إحداثيات خط العرض وخط الطول لـ center، ومستوى التكبير أو التصغير الذي سيتم استخدامه لـ zoom. إذا لزم الأمر، أضِف رقم تعريف خريطة باستخدام السمة mapId. بما أنّ الخريطة ستكون تلقائيًا بتنسيق نقطي، اطلب خريطة متجهة من خلال تحديد خيار الخريطة "VECTOR"، ويُنصح باستخدام نوع الخريطة المتجهة للحصول على أفضل تجربة للمستخدم، لأنّها توفّر دقة بصرية محسّنة بالإضافة إلى إمكانية التحكّم في الميل والاتجاه على الخريطة.

    TypeScript

    let map: google.maps.Map;
    async function initMap(): Promise<void> {
        // Import the needed libraries
        const { Map, RenderingType } = (await google.maps.importLibrary(
            'maps'
        )) as google.maps.MapsLibrary;
    
        // Create a new map from the div with id="map".
        map = new Map(document.getElementById('map') as HTMLElement, {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8,
            renderingType: "VECTOR",
        });
    }
    
    initMap();

    JavaScript

    let map;
    async function initMap() {
        // Import the needed libraries
        const { Map, RenderingType } = (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",
        });
    }
    initMap();

الاطّلاع على رمز المصدر الكامل للمثال

TypeScript

let map: google.maps.Map;
async function initMap(): Promise<void> {
    // Import the needed libraries
    const { Map, RenderingType } = (await google.maps.importLibrary(
        'maps'
    )) as google.maps.MapsLibrary;

    // Create a new map from the div with id="map".
    map = new Map(document.getElementById('map') as HTMLElement, {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8,
        renderingType: "VECTOR",
    });
}

initMap();

JavaScript

let map;
async function initMap() {
    // Import the needed libraries
    const { Map, RenderingType } = (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",
    });
}
initMap();

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>

    <!-- prettier-ignore -->
    <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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly" });</script>
    </body>
</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,
});