1

I have a function to create a Google Map along with some other logic to create markers, infowindows and enable some user interaction to control the map.

When using jQuery and WordPress, by default, the $ function is disabled for compatibility.

To overcome this, I have encapsulated all my JavaScript code inside the following block:

(function ($) {

function initMap() {
console.log("Initmap start");
map = new google.maps.Map(document.getElementById("dealer-map"), {
    center: new google.maps.LatLng(54.583408, -4.125605),
    zoom: 5
});
setMarkers(map);
}

//...other code

}(jQuery));

(Sorry, I'm not sure what the above would be known as, hence the title)

There is then a function callback within the Google Maps API code which calls the initMap(); function once the API has loaded, however this does not work. I attempt to call this manually via the Chrome developer console, but a receive:

ReferenceError: initMap is not defined

Is there any way around this? Or would it be easier to just enable the $ function?

StrattonL
  • 676
  • 1
  • 9
  • 23

2 Answers2

0

Every time you use the function keyword, you are creating a new scope. This applies if you are using a function expression or a function statement.

You will need to either use that function in a scope that can see it, or you'll have to export that function to something more public.

I don't know enough about wordpress to discuss how to do that.

function scope1() {
  // This scope is private
  function private() {
  }
}

function scope2() {
  // This is a whole different scope that cannot
  // see anything inside of scope 1.
  function private() {
  }
}
Jeremy J Starcher
  • 22,523
  • 6
  • 52
  • 73
0

Here's three ways to do this:

function initMap() {
  (function($) {
    /*...*/
  })(jQuery);
}

or

function initMap() {
  const $ = jQuery;
  /*...*/
}

or

function init($) {
  /*...*/
}

function initMap() {
  init(jQuery);
}
ChrisG
  • 8,206
  • 4
  • 20
  • 34