إضافة علامة إلى خريطة

اختيار النظام الأساسي: Android‏ iOS‏ JavaScript‏

استخدِم العلامات لعرض مواقع جغرافية فردية على الخريطة. توضّح هذه الصفحة كيفية إضافة علامة إلى خريطة آليًا وباستخدام عناصر HTML مخصّصة.

تحميل مكتبة العلامات المتقدّمة

لإضافة علامة متقدّمة إلى خريطة، يجب أن يحمّل رمز الخريطة مكتبة marker التي توفّر فئتَي AdvancedMarkerElement وPinElement. وينطبق ذلك سواء كان تطبيقك يحمّل العلامات آليًا أو باستخدام HTML. لإجراء ذلك، يجب أن يحمّل تطبيقك أولاً Maps JavaScript API.

تعتمد الطريقة التي تستخدمها لتحميل المكتبات على كيفية تحميل صفحة الويب لـ Maps JavaScript API.

  • إذا كانت صفحة الويب تستخدم تحميل النصوص البرمجية الديناميكية، أضِف مكتبة العلامات واستورِد AdvancedMarkerElement (وPinElement اختياريًا) في وقت التشغيل، كما هو موضّح هنا.

    const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary("marker");
  • إذا كانت صفحة الويب تستخدم علامة تحميل النص البرمجي المباشر، أضِف libraries=marker إلى النص البرمجي للتحميل، كما هو موضّح في المقتطف التالي. سيؤدي ذلك إلى استيراد كل من AdvancedMarkerElement وPinElement.

    <script
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly&libraries=marker"
    defer
    ></script>

ضبط معرّف خريطة

يجب توفّر معرّف خريطة لاستخدام "العلامات المتقدّمة" (يمكن استخدام DEMO_MAP_ID). اضبط معرّف خريطة في خيارات الخريطة، كما هو موضّح هنا:

const map = new Map(document.getElementById('map') as HTMLElement, {
    center: { lat: 37.4239163, lng: -122.0947209 },
    zoom: 14,
    mapId: 'DEMO_MAP_ID',
});

إذا كنت تستخدم مكوّنات الويب، يمكنك ضبط معرّف الخريطة مباشرةً على العنصر gmp-map:

<gmp-map center="37.4239163,-122.0947209" zoom="14" map-id="DEMO_MAP_ID"></gmp-map>

مزيد من المعلومات عن معرّفات الخرائط

إضافة علامة باستخدام عناصر HTML مخصّصة

لإضافة علامة متقدّمة باستخدام عناصر HTML مخصّصة، أضِف عنصرًا فرعيًا gmp-advanced-marker إلى العنصر gmp-map. يوضّح المقتطف التالي كيفية إضافة علامات إلى صفحة ويب:

<gmp-map
    center="41.027748173921374, -92.41852445367961"
    zoom="13"
    map-id="DEMO_MAP_ID">
    <gmp-advanced-marker
        position="41.027748173921374, -92.41852445367961"
        title="Ottumwa, IA"></gmp-advanced-marker>
</gmp-map>

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

يوضّح هذا المثال كيفية إنشاء خريطة تتضمّن علامات باستخدام HTML.

TypeScript

// This example adds a map with markers, using web components.

JavaScript

// This example adds a map with markers, using web components.

CSS

/* Note: This CSS file is intentionally blank. */

HTML

<html>
    <head>
        <title>Add a Map with Markers using HTML</title>
        <style>
            gmp-map {
                height: 100%;
            }
            html,
            body {
                height: 100%;
                margin: 0;
                padding: 0;
            }
        </style>
        <script type="module" src="./index.js"></script>
        <script
            async
            src="https://maps.googleapis.com/maps/api/js?loading=async&key=GOOGLE_MAPS_API_KEY&libraries=maps,marker"></script>
    </head>
    <body>
        <gmp-map
            center="41.027748173921374, -92.41852445367961"
            zoom="13"
            map-id="DEMO_MAP_ID">
            <gmp-advanced-marker
                position="41.027748173921374, -92.41852445367961"
                title="Ottumwa, IA"></gmp-advanced-marker>
        </gmp-map>
    </body>
</html>

إضافة علامة آليًا

لإضافة علامة متقدّمة إلى خريطة بشكل آلي، أنشئ AdvancedMarkerElement جديدًا وألحِقه بالخريطة كما هو موضّح في هذا المثال:

TypeScript

const mapElement = document.querySelector('gmp-map')!;

async function init() {
    // Request needed libraries.
    const [{ AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('maps'),
    ]);

    const marker = new AdvancedMarkerElement({
        position: { lat: 37.4239163, lng: -122.0947209 },
    });
    mapElement.append(marker);
}

JavaScript

const mapElement = document.querySelector('gmp-map');

async function init() {
    // Request needed libraries.
    const [{ AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('maps'),
    ]);

    const marker = new AdvancedMarkerElement({
        position: { lat: 37.4239163, lng: -122.0947209 },
    });
    mapElement.append(marker);
}

لا يمكن إلحاق العناصر إلا عند استخدام مكوّنات الويب. إذا تم استخدام العنصر div لتحميل الخريطة، استخدِم السمة map لربط العلامة بمثيل الخريطة كما هو موضّح هنا:

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

const marker = new AdvancedMarkerElement({
    map: myMap,
    position: { lat: -34.397, lng: 150.644 },
});

إزالة علامة

لإزالة علامة من الخريطة، اضبط marker.map أو marker.position على null.

// Set the map to null.
marker.map = null;

// Set the position to null.
marker.position = null;

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

يوضّح هذا المثال كيفية إضافة علامة إلى خريطة.

TypeScript

const mapElement = document.querySelector('gmp-map')!;

async function init() {
    // Request needed libraries.
    const [{ AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('maps'),
    ]);

    const marker = new AdvancedMarkerElement({
        position: { lat: 37.4239163, lng: -122.0947209 },
    });
    mapElement.append(marker);
}
void init();

JavaScript

const mapElement = document.querySelector('gmp-map');

async function init() {
    // Request needed libraries.
    const [{ AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('maps'),
    ]);

    const marker = new AdvancedMarkerElement({
        position: { lat: 37.4239163, lng: -122.0947209 },
    });
    mapElement.append(marker);
}
void init();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
gmp-map {
    height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
    height: 100%;
    margin: 0;
    padding: 0;
}

HTML

<html>
    <head>
        <title>Default Advanced Marker</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: "GOOGLE_MAPS_API_KEY"
            });
        </script>
    </head>
    <body>
        <gmp-map
            center="37.4239163,-122.0947209"
            zoom="14"
            map-id="4504f8b37365c3d0"></gmp-map>
    </body>
</html>

الخطوات التالية