Giriş
Yer paylaşımları, haritada enlem/boylam koordinatlarına bağlı olan nesnelerdir. Bu nedenle, haritayı sürüklediğinizde veya yakınlaştırdığınızda hareket ederler. Önceden tanımlanmış yer paylaşımı türleri hakkında bilgi için Harita üzerinde çizim yapma başlıklı makaleyi inceleyin.
Maps JavaScript API, kendi özel yer paylaşımlarınızı oluşturmanız için bir OverlayView sınıfı sağlar. OverlayView, yer paylaşımlarınızı oluştururken uygulamanız gereken çeşitli yöntemler sağlayan bir temel sınıftır. Sınıf, ekran koordinatları ile haritadaki konumlar arasında çeviri yapmayı mümkün kılan birkaç yöntem de sunar.
Özel yer paylaşımı ekleme
Özel yer paylaşımı oluşturmak için gereken adımların özeti aşağıda verilmiştir:
- Özel yer paylaşımı nesnenizin
prototypedeğerini yeni birgoogle.maps.OverlayView()örneğine ayarlayın. Bu işlem, yer paylaşımı sınıfının alt sınıfını oluşturur. - Özel yer paylaşımınız için bir kurucu oluşturun ve başlatma parametrelerini ayarlayın.
- Prototipinizde bir
onAdd()yöntemi uygulayın ve yer paylaşımını haritaya ekleyin. Harita, yer paylaşımının eklenmesi için hazır olduğundaOverlayView.onAdd()çağrılır. - Prototipinizde bir
draw()yöntemi uygulayın ve nesnenizin görsel görünümünü yönetin. Nesne ilk kez gösterildiğindeOverlayView.draw()çağrılır. - Ayrıca, yer paylaşımlı reklamda eklediğiniz tüm öğeleri temizlemek için bir
onRemove()yöntemi de uygulamanız gerekir.
Her adımla ilgili daha fazla bilgiyi aşağıda bulabilirsiniz. Çalışan örnek kodun tamamını görebilirsiniz: Örnek kodu görüntüleyin.
Yer paylaşımını alt sınıfa ayırma
Aşağıdaki örnekte, basit bir görüntü bindirme oluşturmak için OverlayView kullanılmaktadır.
Şimdi USGSOverlay sınıfı için bir kurucu oluşturup iletilen parametreleri yeni nesnenin özellikleri olarak başlatıyoruz.
TypeScript
/** * The custom USGSOverlay object contains the USGS image, * the bounds of the image, and a reference to the map. */ class USGSOverlay extends google.maps.OverlayView { private bounds: google.maps.LatLngBounds; private image: string; private div?: HTMLElement; constructor(bounds: google.maps.LatLngBounds, image: string) { super(); this.bounds = bounds; this.image = image; }
JavaScript
/** * The custom USGSOverlay object contains the USGS image, * the bounds of the image, and a reference to the map. */ class USGSOverlay extends google.maps.OverlayView { bounds; image; div; constructor(bounds, image) { super(); this.bounds = bounds; this.image = image; }
Bu yer paylaşımını, yer paylaşımının oluşturucusundaki haritaya henüz ekleyemiyoruz. Öncelikle, haritadaki tüm bölmelerin kullanılabilir olduğundan emin olmamız gerekir. Çünkü bu bölmeler, nesnelerin haritada hangi sırayla gösterileceğini belirler. API, bu durumun gerçekleştiğini belirten bir yardımcı yöntem sağlar. Bu yöntemi bir sonraki bölümde ele alacağız.
Yer paylaşımını başlatma
Yer paylaşımı ilk kez örneklendirildiğinde ve görüntülenmeye hazır olduğunda tarayıcının DOM'u aracılığıyla haritaya eklememiz gerekir. API, yer paylaşımının onAdd() yöntemini çağırarak yer paylaşımının haritaya eklendiğini belirtir. Bu yöntemi işlemek için resmimizi tutacak bir <div> oluşturur, bir <img> öğesi ekler, bunu <div> öğesine ekler ve ardından yer paylaşımını haritanın bölmelerinden birine ekleriz. Panel, DOM ağacındaki bir düğümdür.
MapPanes türündeki paneller, haritadaki farklı katmanların yığın sırasını belirtir. Aşağıdaki bölmeler kullanılabilir ve aşağıdan yukarıya doğru sıralanmıştır:
mapPaneen alttaki paneldir ve karoların üzerinde yer alır. DOM etkinliklerini alamayabilir. (Pane 0).overlayLayer; çoklu çizgiler, poligonlar, yer yer paylaşımları ve karo katmanı yer paylaşımları içerir. DOM etkinlikleri almayabilir. (Pane 1).markerLayerişaretçi içeriyor. DOM etkinlikleri almayabilir. (2. bölme).overlayMouseTarget, DOM etkinliklerini alan öğeler içeriyor. (3. bölme).floatPane, bilgi penceresini içerir. Tüm harita yerleşimlerinin üzerinde yer alır. (4. bölme).
Resmimiz bir "yer yer paylaşımı" olduğundan overlayLayer bölmesini kullanacağız. Bu bölmeyi oluşturduktan sonra nesnemizi alt öğe olarak ekleyeceğiz.
TypeScript
/** * onAdd is called when the map's panes are ready and the overlay has been * added to the map. */ onAdd() { this.div = document.createElement("div"); this.div.style.borderStyle = "none"; this.div.style.borderWidth = "0px"; this.div.style.position = "absolute"; // Create the img element and attach it to the div. const img = document.createElement("img"); img.src = this.image; img.style.width = "100%"; img.style.height = "100%"; img.style.position = "absolute"; this.div.appendChild(img); // Add the element to the "overlayLayer" pane. const panes = this.getPanes()!; panes.overlayLayer.appendChild(this.div); }
JavaScript
/** * onAdd is called when the map's panes are ready and the overlay has been * added to the map. */ onAdd() { this.div = document.createElement("div"); this.div.style.borderStyle = "none"; this.div.style.borderWidth = "0px"; this.div.style.position = "absolute"; // Create the img element and attach it to the div. const img = document.createElement("img"); img.src = this.image; img.style.width = "100%"; img.style.height = "100%"; img.style.position = "absolute"; this.div.appendChild(img); // Add the element to the "overlayLayer" pane. const panes = this.getPanes(); panes.overlayLayer.appendChild(this.div); }
Yer paylaşımını çizme
Yukarıdaki kodda herhangi bir özel görsel görüntüleme çağırmadığımızı unutmayın. API, ilk ekleme de dahil olmak üzere harita üzerinde yer paylaşımı çizmesi gerektiğinde yer paylaşımında ayrı bir draw() yöntemini çağırır.
Bu nedenle, bu draw() yöntemini uygulayacağız, getProjection() kullanarak yer paylaşımının MapCanvasProjection değerini alacağız ve nesnenin sağ üst ve sol alt noktalarını sabitleyeceğimiz tam koordinatları hesaplayacağız.
Ardından <div> boyutunu değiştirebiliriz. Bu işlem, resmi yer paylaşımının oluşturucusunda belirttiğimiz sınırlara uyacak şekilde yeniden boyutlandırır.
TypeScript
draw() { // We use the south-west and north-east // coordinates of the overlay to peg it to the correct position and size. // To do this, we need to retrieve the projection from the overlay. const overlayProjection = this.getProjection(); // Retrieve the south-west and north-east coordinates of this overlay // in LatLngs and convert them to pixel coordinates. // We'll use these coordinates to resize the div. const sw = overlayProjection.fromLatLngToDivPixel( this.bounds.getSouthWest() )!; const ne = overlayProjection.fromLatLngToDivPixel( this.bounds.getNorthEast() )!; // Resize the image's div to fit the indicated dimensions. if (this.div) { this.div.style.left = sw.x + "px"; this.div.style.top = ne.y + "px"; this.div.style.width = ne.x - sw.x + "px"; this.div.style.height = sw.y - ne.y + "px"; } }
JavaScript
draw() { // We use the south-west and north-east // coordinates of the overlay to peg it to the correct position and size. // To do this, we need to retrieve the projection from the overlay. const overlayProjection = this.getProjection(); // Retrieve the south-west and north-east coordinates of this overlay // in LatLngs and convert them to pixel coordinates. // We'll use these coordinates to resize the div. const sw = overlayProjection.fromLatLngToDivPixel( this.bounds.getSouthWest(), ); const ne = overlayProjection.fromLatLngToDivPixel( this.bounds.getNorthEast(), ); // Resize the image's div to fit the indicated dimensions. if (this.div) { this.div.style.left = sw.x + "px"; this.div.style.top = ne.y + "px"; this.div.style.width = ne.x - sw.x + "px"; this.div.style.height = sw.y - ne.y + "px"; } }
Özel yer paylaşımını kaldırma
Ayrıca, yer paylaşımını haritadan tamamen kaldırmak için bir onRemove() yöntemi ekleriz.
TypeScript
/** * The onRemove() method will be called automatically from the API if * we ever set the overlay's map property to 'null'. */ onRemove() { if (this.div) { (this.div.parentNode as HTMLElement).removeChild(this.div); delete this.div; } }
JavaScript
/** * The onRemove() method will be called automatically from the API if * we ever set the overlay's map property to 'null'. */ onRemove() { if (this.div) { this.div.parentNode.removeChild(this.div); delete this.div; } }
Özel yer paylaşımını gizleme ve gösterme
Bir yer paylaşımını oluşturmak veya kaldırmak yerine gizlemek ya da göstermek istiyorsanız yer paylaşımının görünürlüğünü ayarlamak için kendi hide() ve show() yöntemlerinizi uygulayabilirsiniz. Alternatif olarak, yer paylaşımını haritanın DOM'undan ayırabilirsiniz ancak bu işlem biraz daha maliyetlidir. Yer paylaşımını haritanın DOM'una yeniden eklerseniz yer paylaşımının onAdd() yöntemini yeniden çağıracağını unutmayın.
Aşağıdaki örnekte, yer paylaşımının prototipine hide() ve show() yöntemleri eklenmektedir. Bu yöntemler, <div> kapsayıcısının görünürlüğünü açıp kapatır. Ayrıca, yer paylaşımını haritaya ekleyen veya haritadan ayıran bir toggleDOM() yöntemi ekleriz.
TypeScript
/** * Set the visibility to 'hidden' or 'visible'. */ hide() { if (this.div) { this.div.style.visibility = "hidden"; } } show() { if (this.div) { this.div.style.visibility = "visible"; } } toggle() { if (this.div) { if (this.div.style.visibility === "hidden") { this.show(); } else { this.hide(); } } } toggleDOM(map: google.maps.Map) { if (this.getMap()) { this.setMap(null); } else { this.setMap(map); } }
JavaScript
/** * Set the visibility to 'hidden' or 'visible'. */ hide() { if (this.div) { this.div.style.visibility = "hidden"; } } show() { if (this.div) { this.div.style.visibility = "visible"; } } toggle() { if (this.div) { if (this.div.style.visibility === "hidden") { this.show(); } else { this.hide(); } } } toggleDOM(map) { if (this.getMap()) { this.setMap(null); } else { this.setMap(map); } }
Düğme kontrolleri ekleme
toggle ve toggleDom yöntemlerini tetiklemek için haritaya düğme kontrolleri eklenir.
TypeScript
const toggleButton = document.createElement("button"); toggleButton.textContent = "Toggle"; toggleButton.classList.add("custom-map-control-button"); const toggleDOMButton = document.createElement("button"); toggleDOMButton.textContent = "Toggle DOM Attachment"; toggleDOMButton.classList.add("custom-map-control-button"); toggleButton.addEventListener("click", () => { overlay.toggle(); }); toggleDOMButton.addEventListener("click", () => { overlay.toggleDOM(map); }); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleDOMButton); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleButton);
JavaScript
const toggleButton = document.createElement("button"); toggleButton.textContent = "Toggle"; toggleButton.classList.add("custom-map-control-button"); const toggleDOMButton = document.createElement("button"); toggleDOMButton.textContent = "Toggle DOM Attachment"; toggleDOMButton.classList.add("custom-map-control-button"); toggleButton.addEventListener("click", () => { overlay.toggle(); }); toggleDOMButton.addEventListener("click", () => { overlay.toggleDOM(map); }); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleDOMButton); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleButton);
Örnek kodun tamamı
Örnek kodun tamamı aşağıda verilmiştir:
TypeScript
// This example adds hide() and show() methods to a custom overlay's prototype. // These methods toggle the visibility of the container <div>. // overlay to or from the map. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 11, center: { lat: 62.323907, lng: -150.109291 }, mapTypeId: "satellite", } ); const bounds = new google.maps.LatLngBounds( new google.maps.LatLng(62.281819, -150.287132), new google.maps.LatLng(62.400471, -150.005608) ); // The photograph is courtesy of the U.S. Geological Survey. let image = "https://developers.google.com/maps/documentation/javascript/"; image += "examples/full/images/talkeetna.png"; /** * The custom USGSOverlay object contains the USGS image, * the bounds of the image, and a reference to the map. */ class USGSOverlay extends google.maps.OverlayView { private bounds: google.maps.LatLngBounds; private image: string; private div?: HTMLElement; constructor(bounds: google.maps.LatLngBounds, image: string) { super(); this.bounds = bounds; this.image = image; } /** * onAdd is called when the map's panes are ready and the overlay has been * added to the map. */ onAdd() { this.div = document.createElement("div"); this.div.style.borderStyle = "none"; this.div.style.borderWidth = "0px"; this.div.style.position = "absolute"; // Create the img element and attach it to the div. const img = document.createElement("img"); img.src = this.image; img.style.width = "100%"; img.style.height = "100%"; img.style.position = "absolute"; this.div.appendChild(img); // Add the element to the "overlayLayer" pane. const panes = this.getPanes()!; panes.overlayLayer.appendChild(this.div); } draw() { // We use the south-west and north-east // coordinates of the overlay to peg it to the correct position and size. // To do this, we need to retrieve the projection from the overlay. const overlayProjection = this.getProjection(); // Retrieve the south-west and north-east coordinates of this overlay // in LatLngs and convert them to pixel coordinates. // We'll use these coordinates to resize the div. const sw = overlayProjection.fromLatLngToDivPixel( this.bounds.getSouthWest() )!; const ne = overlayProjection.fromLatLngToDivPixel( this.bounds.getNorthEast() )!; // Resize the image's div to fit the indicated dimensions. if (this.div) { this.div.style.left = sw.x + "px"; this.div.style.top = ne.y + "px"; this.div.style.width = ne.x - sw.x + "px"; this.div.style.height = sw.y - ne.y + "px"; } } /** * The onRemove() method will be called automatically from the API if * we ever set the overlay's map property to 'null'. */ onRemove() { if (this.div) { (this.div.parentNode as HTMLElement).removeChild(this.div); delete this.div; } } /** * Set the visibility to 'hidden' or 'visible'. */ hide() { if (this.div) { this.div.style.visibility = "hidden"; } } show() { if (this.div) { this.div.style.visibility = "visible"; } } toggle() { if (this.div) { if (this.div.style.visibility === "hidden") { this.show(); } else { this.hide(); } } } toggleDOM(map: google.maps.Map) { if (this.getMap()) { this.setMap(null); } else { this.setMap(map); } } } const overlay: USGSOverlay = new USGSOverlay(bounds, image); overlay.setMap(map); const toggleButton = document.createElement("button"); toggleButton.textContent = "Toggle"; toggleButton.classList.add("custom-map-control-button"); const toggleDOMButton = document.createElement("button"); toggleDOMButton.textContent = "Toggle DOM Attachment"; toggleDOMButton.classList.add("custom-map-control-button"); toggleButton.addEventListener("click", () => { overlay.toggle(); }); toggleDOMButton.addEventListener("click", () => { overlay.toggleDOM(map); }); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleDOMButton); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleButton); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example adds hide() and show() methods to a custom overlay's prototype. // These methods toggle the visibility of the container <div>. // overlay to or from the map. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 11, center: { lat: 62.323907, lng: -150.109291 }, mapTypeId: "satellite", }); const bounds = new google.maps.LatLngBounds( new google.maps.LatLng(62.281819, -150.287132), new google.maps.LatLng(62.400471, -150.005608), ); // The photograph is courtesy of the U.S. Geological Survey. let image = "https://developers.google.com/maps/documentation/javascript/"; image += "examples/full/images/talkeetna.png"; /** * The custom USGSOverlay object contains the USGS image, * the bounds of the image, and a reference to the map. */ class USGSOverlay extends google.maps.OverlayView { bounds; image; div; constructor(bounds, image) { super(); this.bounds = bounds; this.image = image; } /** * onAdd is called when the map's panes are ready and the overlay has been * added to the map. */ onAdd() { this.div = document.createElement("div"); this.div.style.borderStyle = "none"; this.div.style.borderWidth = "0px"; this.div.style.position = "absolute"; // Create the img element and attach it to the div. const img = document.createElement("img"); img.src = this.image; img.style.width = "100%"; img.style.height = "100%"; img.style.position = "absolute"; this.div.appendChild(img); // Add the element to the "overlayLayer" pane. const panes = this.getPanes(); panes.overlayLayer.appendChild(this.div); } draw() { // We use the south-west and north-east // coordinates of the overlay to peg it to the correct position and size. // To do this, we need to retrieve the projection from the overlay. const overlayProjection = this.getProjection(); // Retrieve the south-west and north-east coordinates of this overlay // in LatLngs and convert them to pixel coordinates. // We'll use these coordinates to resize the div. const sw = overlayProjection.fromLatLngToDivPixel( this.bounds.getSouthWest(), ); const ne = overlayProjection.fromLatLngToDivPixel( this.bounds.getNorthEast(), ); // Resize the image's div to fit the indicated dimensions. if (this.div) { this.div.style.left = sw.x + "px"; this.div.style.top = ne.y + "px"; this.div.style.width = ne.x - sw.x + "px"; this.div.style.height = sw.y - ne.y + "px"; } } /** * The onRemove() method will be called automatically from the API if * we ever set the overlay's map property to 'null'. */ onRemove() { if (this.div) { this.div.parentNode.removeChild(this.div); delete this.div; } } /** * Set the visibility to 'hidden' or 'visible'. */ hide() { if (this.div) { this.div.style.visibility = "hidden"; } } show() { if (this.div) { this.div.style.visibility = "visible"; } } toggle() { if (this.div) { if (this.div.style.visibility === "hidden") { this.show(); } else { this.hide(); } } } toggleDOM(map) { if (this.getMap()) { this.setMap(null); } else { this.setMap(map); } } } const overlay = new USGSOverlay(bounds, image); overlay.setMap(map); const toggleButton = document.createElement("button"); toggleButton.textContent = "Toggle"; toggleButton.classList.add("custom-map-control-button"); const toggleDOMButton = document.createElement("button"); toggleDOMButton.textContent = "Toggle DOM Attachment"; toggleDOMButton.classList.add("custom-map-control-button"); toggleButton.addEventListener("click", () => { overlay.toggle(); }); toggleDOMButton.addEventListener("click", () => { overlay.toggleDOM(map); }); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleDOMButton); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleButton); } window.initMap = 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; } .custom-map-control-button { background-color: #fff; border: 0; border-radius: 2px; box-shadow: 0 1px 4px -1px rgba(0, 0, 0, 0.3); margin: 10px; padding: 0 0.5em; font: 400 18px Roboto, Arial, sans-serif; overflow: hidden; height: 40px; cursor: pointer; } .custom-map-control-button:hover { background: rgb(235, 235, 235); }
HTML
<html>
<head>
<title>Showing/Hiding Overlays</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
</head>
<body>
<div id="map"></div>
<!--
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&callback=initMap&v=weekly"
defer
></script>
</body>
</html>