Magento – Magento 2 include google maps js only on contact page

google-mapjavascriptmagento2

I have a custom theme based on Luma, I'm trying to include google maps script only on contact page but it's not working.

Here is my contact_index_index.xml file under my-theme/Magento_Contact/layout/contact_index_index.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
    <title>Contact Us</title>

    <!-- Google map -->
    <script src="https://maps.googleapis.com/maps/api/js?key=My-Key" src_type="url" />
    <link src="js/google_init.js"/>

</head>
<body>
    <referenceContainer name="content">
        <block class="Magento\Contact\Block\ContactForm" name="contactForm" template="Magento_Contact::form.phtml">
            <container name="form.additional.info" label="Form Additional Info"/>
        </block>
    </referenceContainer>
</body>
</page>

Google_init.js file is under my_theme/Magento_Contact/web/js/google_init.js

But when I view page source, the scripts included in contact_index_index.xml are not appearing. What am I doing wrong ?

Best Answer

1) app/design/frontend/vendor/your-theme/requirejs-config.js

var config = {
    paths: {
        "jquery.googleapi": "https://maps.googleapis.com/maps/api/js?key=My-Key"
    },
    shim: {
        'jquery.googleapi': {
            'deps': ['jquery']
        }
    },
    deps: [
        "js/google_init"
    ]
};

2) app/design/frontend/vendor/your-theme/Magento_Contact/layout/contact_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="content">
        <block class="Magento\Contact\Block\ContactForm" name="contactForm" template="Magento_Contact::form.phtml">
            <container name="form.additional.info" label="Form Additional Info"/>
        </block>
    </referenceContainer>
</body>
</page>