Haritaya işaretçi ekleme

Platform seçin: Android iOS JavaScript

Haritada tek bir konumu göstermek için işaretçileri kullanın. Bu sayfada, programatik olarak ve özel HTML öğeleri kullanarak haritaya nasıl işaretçi ekleneceği gösterilmektedir.

Gelişmiş işaretçi kitaplığını yükleme

Haritaya gelişmiş işaretçi eklemek için harita kodunuzun AdvancedMarkerElement ve PinElement sınıflarını sağlayan marker kitaplığını yüklemesi gerekir. Bu durum, uygulamanızın işaretçileri programatik olarak veya HTML kullanarak yüklemesi fark etmeksizin geçerlidir. Bunun için uygulamanızın öncelikle Maps JavaScript API'yi yüklemesi gerekir.

Kitaplıkları yüklemek için kullandığınız yöntem, web sayfanızın Maps JavaScript API'yi nasıl yüklediğine bağlıdır.

  • Web sayfanızda dinamik komut dosyası yükleme kullanılıyorsa işaretçi kitaplığını ekleyin ve çalışma zamanında AdvancedMarkerElement (ve isteğe bağlı olarak PinElement) öğesini burada gösterildiği gibi içe aktarın.

    const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary("marker");
  • Web sayfanızda doğrudan komut dosyası yükleme etiketi kullanılıyorsa aşağıdaki snippet'te gösterildiği gibi yükleme komut dosyasına libraries=marker ekleyin. Bunu yaptığınızda hem AdvancedMarkerElement hem de PinElement içe aktarılır.

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

Harita kimliği ayarlama

Gelişmiş işaretçileri kullanmak için harita kimliği gerekir (DEMO_MAP_ID kullanılabilir). Harita seçeneklerinde, aşağıda gösterildiği gibi bir harita kimliği ayarlayın:

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

Web bileşenleri kullanıyorsanız harita kimliğini doğrudan gmp-map öğesinde ayarlayabilirsiniz:

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

Harita kimlikleri hakkında daha fazla bilgi edinin.

Özel HTML öğeleri kullanarak işaretçi ekleme

Özel HTML öğeleri kullanarak gelişmiş işaretçi eklemek için gmp-map öğesine bir gmp-advanced-marker alt öğesi ekleyin. Aşağıdaki snippet'te, bir web sayfasına işaretçi ekleme işlemi gösterilmektedir:

<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>

Eksiksiz örnek kaynak kodunu inceleyin

Bu örnekte, HTML kullanarak işaretçiler içeren bir harita oluşturma işlemi gösterilmektedir.

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>

Programatik olarak işaretçi ekleme

Haritaya programatik olarak gelişmiş işaretçi eklemek için yeni bir AdvancedMarkerElement oluşturun ve bu örnekte gösterildiği gibi haritaya ekleyin:

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);
}

Öğe ekleme yalnızca web bileşenleri kullanılırken mümkündür. Haritayı yüklemek için div öğesi kullanılıyorsa işaretçiyi harita örneğiyle ilişkilendirmek için map özelliğini kullanın. Örnek:

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 },
});

İşaretçiyi kaldırma

Haritadan bir işaretçiyi kaldırmak için marker.map veya marker.position değerini null olarak ayarlayın.

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

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

Eksiksiz örnek kaynak kodunu inceleyin

Bu örnekte, haritaya nasıl işaretçi ekleneceği gösterilmektedir.

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>

Sonraki adımlar