3

Is there any way we can use Google Address plugin related javascript inside an LWC component like we have used inside the Visual force pages like below,

<apex:component >
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&key=XXXXXXXXXXXXXXX"> 
</script>
<script>
function initialize(addressType) {
    // Create the autocomplete object, restricting the search
    // to geographical location types.
    if (addressType == 'Test') {
        autocomplete = new google.maps.places.Autocomplete((document
                .getElementsByClassName('test')[0]), {
            types : [ 'geocode' ]
        });
        // When the user selects an address from the dropdown,
        // populate the address fields in the form.
        google.maps.event.addListener(autocomplete, 'place_changed',
                function() {
                    fillInAddress('test');
                });
    }
    else {
        autocomplete = new google.maps.places.Autocomplete((document
                .getElementsByClassName(addressType)[0]), {
            types : [ 'geocode' ]
        });
        // When the user selects an address from the dropdown,
        // populate the address fields in the form.
        google.maps.event.addListener(autocomplete, 'place_changed',
                function() {
                    fillInAddress(addressType);
                });
    }
}
</script>
</apex:component>
6
  1. You cannot have direct CDN in LWC component. Download the file , create static resource and refer it in LWC component using loadScript.

  2. Create CSP Trusted Sites to google sites so that the static resource js can interact with host site.

  3. Note that I found bug some days back that just by above steps, it may not work. Not sure if its fixed now. So, the workaround is to Whitelist Third-Party Hosts for Lightning Communities. You can do it in any community. I know it sounds weird that for accessing it in normal lightning experience, you need to add it in community, but this is just a work-around if above 2 steps does not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.