PageSourceSearch

https://www.ibs-b.hu/static/default/dist/web-component/es-map/es-map.js

js ibs-b.hu collected 2026-10-03 19:34:27 UTC 9,378 bytes, 296 lines download raw bytes

1/**
2 * @class EsMap
3 * @extends HTMLElement
4 * @classdesc Térkép elem létrehozása. Két elemű web-component. A szűlő es-map adja a keretet és inicializálja
5 * a térképet, a térkép markereket, infoWindow-t pedig a gyermek es-map-marker elemek tartalmazzák.
6 * Ez utóbbiakat dinamikusan lehet hozzáadni és elvenni.
7 * @version 1.0.1
8 */
9
10// import EsMapMarker from "./es-map-marker.js";
11// import EsMapMarker from "http://127.0.0.1:8000/static/default/async/es-map/es-map-marker.js";
12
13class EsMap extends HTMLElement {
14
15    _option = {
16
17        // Térkép alapértelmezett beállításai.
18        map: {
19            center: {lat: 47.14, lng: 19.5},
20            zoom: 3,
21            scrollwheel: false,
22            zoomControl: true,
23            disableDefaultUI: true,
24            // mapTypeId: 'terra in'
25        },
26
27        // További egyedi beállítások.
28        style: null,
29        showOneInfoWindow: true,
30        autoZoom: true,
31    };
32
33
34    constructor() {
35        super();
36        // Konténerek deklacációja
37        this.promise = {};
38        this._markers = [];
39        this._infoWindows = [];
40        this.nextPossibleGeocodeTime;
41        this.defaultGeocodeTimeout = 1000;		// Minimum ennyi időt vár a geocode-ingok között, hogy ne érjük el a limitet per sec.
42
43        // Fallback icon helye. A gyermekek ezt figyelik.
44        this.icon;
45
46        // Árnyéktartalom beállítása
47        this.attachShadow({mode: 'open'});
48        this.shadowRoot.innerHTML = `
49			<style>
50				:host(*) {
51					display: block;
52					width: 100%;
53					/*height: 450px;*/
54				}
55				.map {
56					display: block;
57					width: 100%;
58					height: 100%;
59				}
60				/* infoWindow ablak bezár gombja. */
61				.gm-style-iw.gm-style-iw-c > button {
62                    top: 0 !important;
63                    right: 0 !important;
64				    width: 24px !important;
65				    height: 24px !important;
66					/*background-color: yellow !important;*/
67					background-repeat: no-repeat !important;
68					background-position: 50% 50% !important;
69					background-size: 20px !important;
70					background-image: url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTE5IDYuNDFMMTcuNTkgNUwxMiAxMC41OUw2LjQxIDVMNSA2LjQxTDEwLjU5IDEyTDUgMTcuNTlMNi40MSAxOUwxMiAxMy40MUwxNy41OSAxOUwxOSAxNy41OUwxMy40MSAxMkwxOSA2LjQxWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==") !important;
71				}
72			</style>
73			<div class="map"></div>`;
74        // mapNode azonosítása.
75        this._mapNode = this.shadowRoot.querySelector('.map');
76    }
77
78
79    /**
80     * @name _init
81     * @description Betölti a google maps api-t.
82     * */
83
84    _init(key) {
85        return this.promise.init = new Promise((resolve, reject) => {
86            const id = 'id-es-map-script';
87            const url = `https://maps.googleapis.com/maps/api/js?key=${key}`;
88
89            // Megnézzük van-e már a DOM-ban a keresett script.
90            let script = document.getElementById(id) || document.querySelector(`script[src="${url}"]`);
91
92            // Ha nem találtuk, létrehozzuk és elhelyezzük a DOM-ban.
93            if (!script) {
94                script = document.createElement('script');
95                script.type = 'text/javascript';
96                script.id = id;
97                script.src = url;
98                document.querySelector('head').appendChild(script);
99            }
100
101            // Megvárjuk míg betölt.
102            let timeout = setTimeout(() => reject(), 10000);
103            script.addEventListener('load', () => {
104                clearTimeout(timeout);
105                resolve();
106            });
107        });
108    }
109
110
111    /**
112     * @name _setMap
113     * @description Rádefiniálja a térkép objektumot egy id-ra.
114     * */
115
116    _setMap() {
117        return this.promise.setMap = new Promise(resolve => {
118            // létrehozzuk a térkét objektumot
119            this.map = new google.maps.Map(this._mapNode, this._option.map);
120            // bounds beállítása, hogy később tudjunk erre is zoomolni
121            this.bounds = new google.maps.LatLngBounds();
122            resolve();
123        });
124    }
125
126
127    /**
128     * @name _setStyle
129     * @description Beállítja a térkép stílusát url-ből.
130     * @param {Array} style: lehet tömb json formátumban
131     * @param {String} style: lehet url, ahonnan betöltjük a jsont
132     * */
133
134    _setStyle(style = this._option.style) {
135        return new Promise(resolve => {
136
137            // ha nincs style megadva, átugorjuk
138            if (!style) resolve();
139
140            new Promise(resolve => {
141
142                // ha json (tömb)
143                if (style instanceof Array) resolve(style);
144
145                // ha url (String)
146                if (Object.prototype.toString.call(style) === '[object String]') {
147                    fetch(style)
148                        .then(result => result.json())
149                        .then(result => {
150                            resolve(result);
151                        });
152                }
153
154            }).then((mapStyle) => {
155                let customMapType = new google.maps.StyledMapType(mapStyle, {name: 'Custom Style'});
156                this.map.mapTypes.set('custom_style', customMapType);
157                this.map.setMapTypeId('custom_style');
158            });
159        });
160    }
161
162
163    /**
164     * @name ready
165     * @description Promise figyelő, eltriggeli ha minden btöltődött.
166     * Ehhez igazítjuk a térképelemek felhelyezését. Kívülről hívható!
167     * */
168
169    ready() {
170        return this.promise.ready = new Promise(resolve => {
171            Promise.all([this.promise.init, this.promise.setMap])
172                .then(response => {
173                    // console.log('ready', google);
174                    resolve();
175                });
176        });
177    }
178
179
180    /**
181     * @name attributeChangedCallback
182     * @description Attribútumok változásának figyelése. Ez inicializáláskor is lefut!
183     * */
184
185    attributeChangedCallback(name, oldValue, newValue) {
186
187        // Ha megadtuk a key paramétert, elindítjuk a térkép inicializálását, megjelenítését.
188        if (name === 'key') {
189            this._init(newValue)
190                .then(this._setMap.bind(this))
191                .catch(error => {
192                    console.warn('EsMap: Google Maps API key hasn\'t been added.');
193                    console.warn(error)
194                });
195        }
196
197        // Zoom paraméter
198        if (name === 'zoom') {
199            const zoom = parseInt(newValue)
200            if (!isNaN(zoom)) {
201                // Ha már van térkép objektum, akkor függvénnyel tudjuk beállítani.
202                if (this.map) {
203                    this.map.setZoom(zoom);
204                }
205                // Ha még nincs, akkor a kezdeti értékadással, amit felkap az setMap.
206                else {
207                    this._option.map.zoom = zoom;
208                }
209            }
210        }
211
212        // Ha adtunk meg középpontot, beállítjuk position formátumban.
213        if (name === 'center') {
214            const latlng = newValue.split(',');
215            const position = {
216                lat: parseFloat(latlng[0]),
217                lng: parseFloat(latlng[1])
218            }
219            if (!isNaN(position.lat) && !isNaN(position.lng)) {
220                if (this.map) {
221                    this.map.setCenter(position);
222                } else {
223                    this._option.map.center = position;
224                }
225            } else {
226                console.warn('The lat, lng coordinates are wrong.');
227            }
228        }
229
230        // Szélesség beállítása.
231        if (name === 'width') {
232            this.style.width = newValue;
233        }
234
235        // Magasság beállítása.
236        if (name === 'height') {
237            this.style.height = newValue;
238        }
239
240        // Scroll Wheel engedélyezése.
241        if (name === 'scrollwheel') {
242            this._option.map.scrollwheel = newValue === 'true';
243        }
244
245        // Zoom kontrol engedélyezése.
246        if (name === 'zoom-control') {
247            this._option.map.zoomControl = newValue === 'true';
248        }
249
250        // Alapértelmezett térkép UI elemek engedélyezése.
251        if (name === 'disable-default-ui') {
252            this._option.map.disableDefaultUI = newValue === 'true';
253        }
254
255        // Stylus hozzáadása on the fly, ha már le van renderelve a térkép.
256        if (name === 'map-style') {
257            this.ready().then(() => this._setStyle(newValue));
258        }
259
260        // Elmentjük fallbackként az ikon url-jét.
261        if (name === 'icon') {
262            this.icon = newValue;
263        }
264    }
265
266    _removeAllMarkers() {
267        // console.log(this);
268    }
269
270    connectedCallback() {
271        console.log('es-map connected', this.children.length)
272    }
273
274    /**
275     * paraméterfigyelés
276     * */
277    static get observedAttributes() {
278        return [
279            'key',
280            'zoom',
281            'scrollwheel',
282            'zoom-control',
283            'disable-default-ui',
284            'center',
285            'map-style',
286            'width',
287            'height',
288            'icon',
289            'toggle',
290            'info-window',
291        ];
292    }
293}
294
295customElements.define('es-map', EsMap);
296// customElements.define('es-map-marker', EsMapMarker);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.