odoo.define("ab_openstreetmap.googlemap_widget", function (require) { "use strict"; const AbstractField = require("web.AbstractField"); const fieldRegistry = require("web.field_registry"); const rpc = require("web.rpc"); const GoogleMapWidget = AbstractField.extend({ template: "googlemap_template", start: async function () { await this._super(...arguments); this._waitForMapReady(); }, _waitForMapReady: function () { const mapEl = document.getElementById("mapid"); if (mapEl && mapEl.offsetWidth > 0 && mapEl.offsetHeight > 0) { this._loadGoogle(); } else { setTimeout(() => this._waitForMapReady(), 100); } }, async _loadGoogle() { const apiKey = await rpc.query({ model: "ir.config_parameter", method: "get_param", args: ["google.maps.api_key"], }); const mapId = await rpc.query({ model: "ir.config_parameter", method: "get_param", args: ["google.maps.map_id"], }); if (!window.google || !window.google.maps) { const script = document.createElement("script"); script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&v=weekly&libraries=places,marker`; script.async = true; script.defer = true; script.onload = () => this._initMap(mapId); document.head.appendChild(script); } else { this._initMap(mapId); } }, async _initMap(mapId) { const lat = parseFloat(this.recordData.latitude) || -6.2; const lng = parseFloat(this.recordData.longtitude) || 106.816666; const edit = this.mode === "edit"; const mapEl = document.getElementById("mapid"); if (!mapEl) return; const { Map } = await google.maps.importLibrary("maps"); const { AdvancedMarkerElement } = await google.maps.importLibrary("marker"); const map = new Map(mapEl, { center: { lat, lng }, zoom: 15, mapId: mapId || undefined, }); const marker = new AdvancedMarkerElement({ map, position: { lat, lng }, gmpDraggable: edit, title: "Lokasi", }); if (edit) { marker.addListener("dragend", () => { const pos = marker.position; this.trigger_up("field_changed", { dataPointID: this.dataPointID, changes: { latitude: pos.lat.toString(), longtitude: pos.lng.toString(), }, viewType: this.viewType, }); }); // Search Box (autocomplete) const input = document.createElement("input"); input.type = "text"; input.placeholder = "Cari alamat..."; input.style = "width: 100%; padding: 8px; margin-bottom: 10px;"; mapEl.parentNode.insertBefore(input, mapEl); const autocomplete = new google.maps.places.Autocomplete(input); autocomplete.addListener("place_changed", () => { const place = autocomplete.getPlace(); if (place.geometry) { const loc = place.geometry.location; map.setCenter(loc); marker.position = loc; this.trigger_up("field_changed", { dataPointID: this.dataPointID, changes: { latitude: loc.lat().toString(), longtitude: loc.lng().toString(), }, viewType: this.viewType, }); } }); } }, isSet() { return true; }, }); fieldRegistry.add("googlemap", GoogleMapWidget); });