Fix Google Maps loading: add auth failure handling and remove unnecessary libraries

This commit is contained in:
Flatlogic Bot 2026-01-31 02:53:43 +00:00
parent 0a784beb41
commit e2d742d9ae

View File

@ -155,7 +155,8 @@
<h5 class="modal-title">{% trans "Choose Location" %}</h5> <h5 class="modal-title">{% trans "Choose Location" %}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div> </div>
<div class="modal-body p-0"> <div class="modal-body p-0 position-relative">
<div id="mapError" class="alert alert-danger m-3 d-none"></div>
<div id="map" style="height: 450px; width: 100%;"></div> <div id="map" style="height: 450px; width: 100%;"></div>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
@ -167,30 +168,70 @@
</div> </div>
{% if google_maps_api_key %} {% if google_maps_api_key %}
<script src="https://maps.googleapis.com/maps/api/js?key={{ google_maps_api_key }}&libraries=places"></script>
<script> <script>
// Global Auth Failure Handler (must be defined before script load)
window.gm_authFailure = function() {
const errorDiv = document.getElementById('mapError');
if (errorDiv) {
errorDiv.innerHTML = `
<strong>Google Maps Error:</strong> Authentication failed.
<br>Please check your API Key and enable <strong>Billing</strong> in Google Cloud Console.
<br>Also ensure <strong>Maps JavaScript API</strong> and <strong>Geocoding API</strong> are enabled.
`;
errorDiv.classList.remove('d-none');
}
console.error("Google Maps Auth Failure");
}
let map; let map;
let marker; let marker;
let currentMode = 'pickup'; // 'pickup' or 'delivery' let currentMode = 'pickup'; // 'pickup' or 'delivery'
let mapModal; let mapModal;
let mapInitialized = false;
// This function is called by the Google Maps script when loaded
function initMap() { function initMap() {
console.log("Google Maps API loaded.");
}
function initializeMapInstance() {
if (mapInitialized && map) return;
console.log("Initializing Map Instance...");
const defaultLocation = { lat: 23.5880, lng: 58.3829 }; // Muscat, Oman const defaultLocation = { lat: 23.5880, lng: 58.3829 }; // Muscat, Oman
map = new google.maps.Map(document.getElementById("map"), { const mapElement = document.getElementById("map");
zoom: 12, if (!mapElement) {
center: defaultLocation, console.error("Map element not found!");
}); return;
}
marker = new google.maps.Marker({ try {
map: map, map = new google.maps.Map(mapElement, {
draggable: true, zoom: 12,
animation: google.maps.Animation.DROP, center: defaultLocation,
}); });
map.addListener("click", (e) => { marker = new google.maps.Marker({
placeMarkerAndPanTo(e.latLng, map); map: map,
}); draggable: true,
animation: google.maps.Animation.DROP,
});
map.addListener("click", (e) => {
placeMarkerAndPanTo(e.latLng, map);
});
mapInitialized = true;
} catch (e) {
console.error("Error creating map:", e);
const errorDiv = document.getElementById('mapError');
if (errorDiv) {
errorDiv.innerText = "Error initializing map: " + e.message;
errorDiv.classList.remove('d-none');
}
}
} }
function placeMarkerAndPanTo(latLng, map) { function placeMarkerAndPanTo(latLng, map) {
@ -200,30 +241,37 @@
function openMap(mode) { function openMap(mode) {
currentMode = mode; currentMode = mode;
mapModal = new bootstrap.Modal(document.getElementById('mapModal')); const modalEl = document.getElementById('mapModal');
// Hide previous errors
const errorDiv = document.getElementById('mapError');
if (errorDiv) errorDiv.classList.add('d-none');
mapModal = new bootstrap.Modal(modalEl);
mapModal.show(); mapModal.show();
// Resize map when modal opens // Ensure map is initialized and resized when modal is fully shown
document.getElementById('mapModal').addEventListener('shown.bs.modal', function () { modalEl.addEventListener('shown.bs.modal', function () {
google.maps.event.trigger(map, "resize"); initializeMapInstance();
// Set marker if existing value if (map) {
let latField = document.getElementById(`id_${mode}_lat`); google.maps.event.trigger(map, "resize");
let lngField = document.getElementById(`id_${mode}_lng`);
// Set marker if existing value
if (latField.value && lngField.value) { let latField = document.getElementById(`id_${mode}_lat`);
let loc = { lat: parseFloat(latField.value), lng: parseFloat(lngField.value) }; let lngField = document.getElementById(`id_${mode}_lng`);
marker.setPosition(loc);
map.setCenter(loc); if (latField.value && lngField.value) {
} else { let loc = { lat: parseFloat(latField.value), lng: parseFloat(lngField.value) };
// Default to Muscat if no value marker.setPosition(loc);
map.setCenter({ lat: 23.5880, lng: 58.3829 }); map.setCenter(loc);
}
} }
}); }, { once: true });
} }
function confirmLocation() { function confirmLocation() {
if (!marker.getPosition()) return; if (!marker || !marker.getPosition()) return;
const lat = marker.getPosition().lat(); const lat = marker.getPosition().lat();
const lng = marker.getPosition().lng(); const lng = marker.getPosition().lng();
@ -231,15 +279,14 @@
document.getElementById(`id_${currentMode}_lat`).value = lat; document.getElementById(`id_${currentMode}_lat`).value = lat;
document.getElementById(`id_${currentMode}_lng`).value = lng; document.getElementById(`id_${currentMode}_lng`).value = lng;
// Try reverse geocoding to fill address (optional but nice) // Try reverse geocoding to fill address
const geocoder = new google.maps.Geocoder(); const geocoder = new google.maps.Geocoder();
geocoder.geocode({ location: { lat: lat, lng: lng } }, (results, status) => { geocoder.geocode({ location: { lat: lat, lng: lng } }, (results, status) => {
if (status === "OK" && results[0]) { if (status === "OK" && results[0]) {
// Simple fill of address field if empty
const addrField = document.getElementById(`id_${currentMode}_address`); const addrField = document.getElementById(`id_${currentMode}_address`);
if (!addrField.value) { addrField.value = results[0].formatted_address;
addrField.value = results[0].formatted_address; } else {
} console.warn("Geocoder failed due to: " + status);
} }
}); });
@ -277,9 +324,7 @@
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
if (data.error) { if (data.error) {
// console.error(data.error); console.error(data.error);
// Maybe show error to user?
// alert(data.error);
} else { } else {
document.getElementById('id_price').value = data.price; document.getElementById('id_price').value = data.price;
document.getElementById('id_distance_km').value = data.distance_km; document.getElementById('id_distance_km').value = data.distance_km;
@ -293,11 +338,15 @@
} }
// Attach listener to weight // Attach listener to weight
document.getElementById('id_weight').addEventListener('change', calculatePrice); const weightInput = document.getElementById('id_weight');
document.getElementById('id_weight').addEventListener('keyup', calculatePrice); if (weightInput) {
weightInput.addEventListener('change', calculatePrice);
weightInput.addEventListener('keyup', calculatePrice);
}
window.initMap = initMap; window.initMap = initMap;
</script> </script>
<script src="https://maps.googleapis.com/maps/api/js?key={{ google_maps_api_key }}&loading=async&callback=initMap" async defer></script>
{% endif %} {% endif %}
<script> <script>