Adding External Gmap JS to WordPress

I had some working javascript code that I wanted to move out of the template file and put into a .js file.

I moved the code into a front.js file, where some pre-existing javascript lives.

Now I'm trying to add the Google Maps API javascript file like so:

/**
 * load css/js into frontend pages
 */
function eng_dealer_map_css_js()
{
    # removed CSS as is irrelevant

    # add js
    wp_register_script(
        'eng_dm_front',
        plugins_url('pub/js/front.js', __FILE__),
        ['gmap'],
        null,
        true
    );

    wp_register_script(
        'gmap',
        'https://maps.googleapis.com/maps/api/js?key=APIKEYcallback=initMaplibraries=geometry',
        [],
        null,
        null
    );

    # register js
    wp_enqueue_script('eng_dm_front');
    wp_enqueue_script('gmap');
}

# actions
add_action('wp_enqueue_scripts', 'eng_dealer_map_css_js');

Now, refreshing the page gets this error in console (without ref file or line number):

uncaught exception: Object

Which isn't the expected behaviour. I'd hope to separate the JS and call the Google Maps API via WP but it seems to not like it that way.

I then inspected the DOM, which shows this:

head
    !-- all the other stuff --
    script src="https://maps.googleapis.com/maps/api/js?key=APIKEYcallback=initMaplibraries=geometry"/script

    script type="text/javascript" charset="UTF-8" src="https://maps.googleapis.com/maps-api-v3/api/js/39/6/intl/en_gb/common.js"/script
    script type="text/javascript" charset="UTF-8" src="https://maps.googleapis.com/maps-api-v3/api/js/39/6/intl/en_gb/util.js"/script
    !-- all the other stuff --
/head
body
    !-- rest of code --
    !--#site-footer--
    script src="http://dev.wp.local/wp-content/plugins/myplugin/pub/js/front.js"/script
/body

It looks like it loads in the correct order, but for whatever reason, it doesn't work when my google maps javascript is in the front.js file and everything is loaded this way. It works when I do it like this:

!-- rest of template code --
script async defer
        src="https://maps.googleapis.com/maps/api/js?key=APIKEYcallback=initMaplibraries=geometry"/script

script
    //my maps JS
/script

How do I import the Google Maps API javascript file and make use of it in my own scripts?

Edit: front.js

//google map stuff
let map;

function calcDistance(lat1, lng1, lat2, lng2)
{
    return convertToMiles(google.maps.geometry.spherical.computeDistanceBetween(
        new google.maps.LatLng(lat1, lng1),
        new google.maps.LatLng(lat2, lng2)
    ))
}

function displayRoute(a, b)
{
    let start = new google.maps.LatLng(a.lat, a.lng),
        end = new google.maps.LatLng(b.lat, b.lng),
        directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get "DirectionsRendererOptions" object

    directionsDisplay.setMap(map); // map should be already initialized.

    let request = {origin : start, destination : end, travelMode : google.maps.TravelMode.DRIVING},
        directionsService = new google.maps.DirectionsService();

    directionsService.route(request, function(response, status)
    {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response)
        }
    })
}

function convertToMiles(i)
{
    return i*0.000621371192
}

function initMap(addr)
{
    let point = new google.maps.LatLng(50.833206,-0.223977),
        search = 0;

    addr = addr || 0;

    if (addr !== 0) {
        addr = JSON.parse(addr);
        point = new google.maps.LatLng(addr[0].lat, addr[0].lng);
        search = addr[0];
    }

    map = new google.maps.Map(document.getElementById('dealer-map'), {
        zoom: 5,
        center: point
    });

    let infowin = new google.maps.InfoWindow;

    $.ajax({
        type: 'get',
        url: '/path/to/file.json',
        success: function(res)
        {
            create_markers(map, infowin, res, search)
        },
        error: function(res)
        {
            console.log(res)
        }
    })
}

function add_conversion()
{
    console.log(this);
    let id = this.dataset.id;

    console.log(id);
}

function create_markers(map, infoWin, dealers, search)
{
    for (const [key, el] of Object.entries(dealers))
    {
        if (search != 0) {
            let dist = calcDistance(el.lat, el.lng, search.lat, search.lng).toFixed(2);

            $('.distance[data-id="'+ el.id +'"]').text(dist+ 'mi');
            $('.dealer[data-id="'+ el.id +'"]').append(
                'div class="col-sm-12"' +
                '    button type="button"' +
                '            class="directions-btn"' +
                '            data-lat="'+ el.lat +'"' +
                '            data-lng="'+ el.lng +'"' +
                '            data-ulat="'+ search.lat +'"' +
                '            data-ulng="'+ search.lng +'"' +
                '        spanDirections/span' +
                '    /button' +
                '/div'
            )
        } else {
            $('.dealer[data-id="'+ el.id +'"]').find('.directions-btn').parent().remove()
        }

        // marker props
        let www = el.www;

        let marker = new google.maps.Marker({
            map: map,
            icon: el.icon,
            position: new google.maps.LatLng(parseFloat(el.lat), parseFloat(el.lng))
        });

        // create html
        let infwindow = document.createElement('div'),
            h = document.createElement('p'),
            p = document.createElement('p'),
            a = document.createElement('a'),
            btn = document.createElement('a'),
            br = document.createElement('br');

        h.textContent = el.name;
        h.style = 'font-weight: 700';

        p.textContent = el.address;

        if (www.length  0) {
            a.textContent = www;
            a.href = www;
            a.target = '_blank';
        }

        btn.textContent = 'click to contact';
        btn.href = 'javascript:add_conversion()';
        btn.classList.add('btn', 'btn-primary');
        btn.dataset.id = el.id;
        btn.dataset.email = el.email;

        infwindow.appendChild(h);
        infwindow.appendChild(p);

        if (www.length  0) {
            infwindow.appendChild(a);
        }

        if (is_mob()) {
            let tel = document.createElement('a');

            //tel.href = 'tel:'+ el.tel;
            tel.href = 'tel:01232141324';
            tel.target = '_blank';
            tel.textContent = 'Call';

            infwindow.appendChild(tel)
        }

        infwindow.appendChild(br);
        infwindow.appendChild(br);
        infwindow.appendChild(btn);

        marker.addListener('click', function()
        {
            infoWin.setContent(infwindow);
            infoWin.open(map, marker)
        })
    }
}

Above wrapped in

jQuery(document).ready(function($){
})

have also tried to put outside the .ready() and same error

Topic google-maps wp-enqueue-script plugin-development Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.