| 1 |
"use strict"; |
| 2 |
|
| 3 |
(function ($) { |
| 4 |
'use strict'; |
| 5 |
|
| 6 |
var apiKeyInput = $('.merchant-module-page-setting-field[data-id="api_key"] input'); |
| 7 |
var addressInput = $('#merchant-address-autocomplete'); |
| 8 |
|
| 9 |
/** |
| 10 |
* Check if the API key is valid and activate Autocomplete |
| 11 |
*/ |
| 12 |
function activateAutocompleteIfNeeded() { |
| 13 |
var apiKey = apiKeyInput.val(); |
| 14 |
if (apiKey && validateApiKey(apiKey)) { |
| 15 |
loadGoogleMapsScript(apiKey); |
| 16 |
} else { |
| 17 |
deactivateAutocomplete(); |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
// Trigger activation on page load |
| 22 |
activateAutocompleteIfNeeded(); |
| 23 |
|
| 24 |
// Handle changes to the API key input |
| 25 |
apiKeyInput.on('input', activateAutocompleteIfNeeded); |
| 26 |
|
| 27 |
/** |
| 28 |
* Load the Google Maps script |
| 29 |
* @param apiKey |
| 30 |
*/ |
| 31 |
function loadGoogleMapsScript(apiKey) { |
| 32 |
deactivateAutocomplete(); |
| 33 |
var scriptURL = "https://maps.googleapis.com/maps/api/js?key=".concat(apiKey, "&libraries=places"); |
| 34 |
$.getScript(scriptURL, function () { |
| 35 |
// Create Google Places Autocomplete instance |
| 36 |
new google.maps.places.Autocomplete(addressInput.get(0), { |
| 37 |
types: ['geocode'] |
| 38 |
}); |
| 39 |
}); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Check the API key length is valid |
| 44 |
* @param apiKey |
| 45 |
* @returns {boolean} |
| 46 |
*/ |
| 47 |
function validateApiKey(apiKey) { |
| 48 |
return apiKey.length === 39; |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Disable Autocomplete for the address input. |
| 53 |
*/ |
| 54 |
function deactivateAutocomplete() { |
| 55 |
var _window$google; |
| 56 |
if ((_window$google = window.google) !== null && _window$google !== void 0 && _window$google.maps) { |
| 57 |
delete google.maps; |
| 58 |
document.querySelectorAll("script").forEach(function (script) { |
| 59 |
if (script.src.includes("googleapis.com/maps") || script.src.includes("maps.gstatic.com")) { |
| 60 |
script.remove(); |
| 61 |
} |
| 62 |
}); |
| 63 |
resetAddressField(); |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Reset the address input field |
| 69 |
*/ |
| 70 |
function resetAddressField() { |
| 71 |
addressInput.val(''); |
| 72 |
addressInput.css({ |
| 73 |
'background-image': 'none' |
| 74 |
}); |
| 75 |
addressInput.attr('disabled', false); |
| 76 |
addressInput.attr('placeholder', merchant_admin_address_autocomplete.field_placeholder); |
| 77 |
} |
| 78 |
})(jQuery); |