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

يمكنك إضافة خريطة Google إلى صفحة ويب باستخدام رموز HTML وCSS وJavaScript. توضّح هذه الصفحة طريقة إضافة خريطة إلى صفحة ويب بطريقتين، وهما: استخدام عنصر HTML المخصّص gmp-map وباستخدام عنصر div.

نظرة عامة

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

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

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

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

  1. في صفحة HTML، أضِف عنصر script يحتوي على شريط التمهيد الذي تم إعداده باستخدام مفتاح واجهة برمجة التطبيقات وأي خيارات أخرى. في مثال مقطع التشغيل التالي، تم حذف معلَمة callback لأنّها ليست مطلوبة.

    <script
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=maps&v=beta" defer>
    </script>
    

  2. في صفحة HTML، أضِف عنصر gmp-map. حدِّد إحداثيات خط العرض وخط الطول لـ center، وقيمة تكبير/تصغير لـ zoom. في هذا المثال، تم تحديد سمة النمط height أيضًا.

    <gmp-map
      center="37.4220656,-122.0840897"
      zoom="10"
      map-id="DEMO_MAP_ID"
      style="height: 400px"
    ></gmp-map>

إكمال نموذج الرمز البرمجي

<html>
  <head>
    <title>Add a Map using HTML</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <gmp-map
      center="37.4220656,-122.0840897"
      zoom="10"
      map-id="DEMO_MAP_ID"
      style="height: 400px"
    ></gmp-map>

    <!-- 
      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&libraries=maps&v=beta"
      defer
    ></script>
  </body>
</html>

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

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

  1. في صفحة HTML، أضِف عنصر script يحتوي على برنامج تحميل الإقلاع الذي تم ضبطه على مفتاح واجهة برمجة التطبيقات الخاص بك وأي خيارات أخرى. ويمكنك بدلاً من ذلك إضافة رمز برنامج تحميل التمهيد مباشرةً إلى ملف TypeScript أو JavaScript، بدون علامات script.

    <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>
    
  2. في صفحة HTML، أضِف عنصر div لتضمين الخريطة.

    <div id="map"></div>
    
  3. في خدمة مقارنة الأسعار (CSS)، اضبط ارتفاع الخريطة على 100%.

    #map {
      height: 100%;
    }
    
  4. في ملف JavaScript، أنشِئ دالة لتحميل مكتبة maps وإعداد الخريطة. حدِّد إحداثيات خط العرض وخط الطول للمكان center، ومستوى التكبير الذي تريد استخدامه مع السمة zoom.

let map;

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");

  map = new Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

initMap();

إكمال نموذج الرمز البرمجي

TypeScript

let map: google.maps.Map;
async function initMap(): Promise<void> {
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  map = new Map(document.getElementById("map") as HTMLElement, {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

initMap();

JavaScript

let map;

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");

  map = new Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

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>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="map"></div>

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

تجربة "عيّنة"