I'm trying to add a map in Contact page. In order to do that,I did the following:
In file: app/design/frontend/MyCompany/MyTheme/Magento_Contact/layout/contact_index_index.xml
I added:
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="cms_page_layout" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>Contact</title>
<css src="css/leaflet.css" />
<script src="js/leaflet.js" />
</head>
</page>
Files are indeed added in page's <head>
.
Then in:
app/design/frontend/MyCompany/MyTheme/Magento_Contact/templates/map.phtml
I added:
<script type="text/javascript">
require(['jquery'], function($){
jQuery(document).ready(function(){
var map = L.map('mapid').setView([40.591110, 23.037170], 15);
});
})
</script>
The last thing I tried was to wrap the code between require(['jquery'], function($){ ...... })
in leaflet.js
file.
Based on similar issues, this should be enough to have the script working. But instead of that I'm getting javascript error in page:
ReferenceError: L is not defined
Please let me know if anyone.
-----SOLUTION BASED ON @PRINCE ANSWER----
app/design/frontend/MyCompany/MyTheme/Magento_Contact/layout/contact_index_index.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="cms_page_layout" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>Contact</title>
<css src="css/leaflet.css" />
<script src="js/leaflet.js" />
</head>
</page>
app/design/frontend/MyCompany/MyTheme/Magento_Contact/templates/map.phtml
<script type="text/javascript">
require(['jquery', 'leaflet', 'my-custom-contact-js'], function($, L, scriptContact) {
scriptContact();
});
</script>
app/design/frontend/MyCompany/MyTheme/Magento_Contact/web/js/custom-js-contact.js
define(['jquery','leaflet'], function($,L) {
return function scriptContact() {
Your js content goes here.
}
});
app/design/frontend/MyCompany/MyTheme/requirejs-config.js
var config = {
map: {
'*': {
'my-custom-contact-js' : 'Magento_Contact/js/custom-js-contact'
}
},
paths: {
'leaflet': 'js/leaflet',
},
shim: {
leaflet: {
exports: 'L'
}
}
};