I am developing a Joomla 3.x content plugin to display Openlayer maps in articles based on @Robbie Jacksons excellent tutorial at https://docs.joomla.org/J3.x:Developing_an_MVC_Component/Adding_a_Map and I managed to make it work. However, in Robbie's tutorial he includes the full Openlayers library which is discouraged for production sites:
// everything's dependent upon JQuery
JHtml::_('jquery.framework');
// we need the Openlayers JS and CSS libraries
$document->addScript("https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol.js");
$document->addStyleSheet("https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol.css");
At the Openlayers website you are encouraged to "include" only the libraries required by your application and "compile" (the correct term is "transpile") a production version ("bundle"). Everything is built on node.js, see eg. https://openlayers.org/en/latest/doc/tutorials/bundle.html. In the production bundle you will find an index.html file referencing the transpiled Javascript code in another file, typically main.js The compiled/minified/obfuscated/uglified Javascript code is higly unreadable but there is a .js.map file to help you map that code into something readable. But even if you know that your function is in there, you cannot call it. Everything is named something else.
I ran into a number of problems when trying to put the transpiled bundle into my Joomla extension:
- In the examples at https://openlayers.org/en/latest/examples/, the Javascript code is invoked by a
<script>
tag just before the final</body>
tag in an HTML file. But what you do in Joomla 3x is, that you put the Javascript declaration in the<head>
section by manipulating the DOM-tree (see https://docs.joomla.org/J3.x:Adding_JavaScript_and_CSS_to_the_page). But it does not get triggered and it is very hard in Joomla plugins to put something just prior to the ending</body>
tag. But you do not want it to run until the DOM-tree is ready, otherwise it will fail. - I need to transfer options from my server-side PHP code to my client-side Openlayer Javascript. The Joomla 3x recommended method is described in https://docs.joomla.org/J3.x:Adding_JavaScript_and_CSS_to_the_page: At serverside you use
$document->addScriptOptions()
and then you retrive the options client side using e.g. varmyOptions = Joomla.getOptions('mod_example');
But you cannot compile and test Javascript code containing Joomla specific code. Node.js does not know whatJoomla.getOptions()
means.
Please advise.