Advertisement

Issues using Google Maps with Joomla?

For Joomla! 5.x Coding related discussions, you could also use: http://groups.google.com/group/joomla-dev-general

Moderators: ooffick, General Support Moderators

Forum rules
Forum Rules
Absolute Beginner's Guide to Joomla! <-- please read before posting, this means YOU.
Forum Post Assistant - If you are serious about wanting help, you will use this tool to help you post.
Windows Defender SmartScreen Issues <-- please read this if using Windows 10.
Post Reply
SocketPup
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 134
Joined: Thu Mar 14, 2024 7:00 am

Issues using Google Maps with Joomla?

Post by SocketPup » Sat May 11, 2024 4:05 am

So in my Joomla project I use Google Maps. The map shows up 90% of the time. However, whenever it doesn't the console gives me this error:

Image

I load the map-related scripts through joomla.asset, like this:

Code: Select all

{
  "$schema": "https://developer.joomla.org/schemas/json-schema/web_assets.json",
  "name": "Gardentemplate",
  "version": "4.0.0",
  "description": "This file contains assets used by gardentemplate",
  "license": "GPL-2.0-or-later",
  "assets": [
    {
      "name": "mystyle",
      "type": "style",
      "uri": "style.css"
    },
    {
      "name": "myscript",
      "type": "script",
      "uri": "script.js",
      "attributes": {
        "defer": true
      }
    },
    {
      "name": "callmapscript",
      "type": "script",
      "uri": "https://maps.googleapis.com/maps/api/js?key=xxx&libraries=places&callback=initMap",
      "attributes": {
        "defer": true,
        "async": true
      }
    }
  ]
}

The js script:

Code: Select all

// Initialize and add the map
    function initMap() {
const fetchedAdress = document.querySelector(".adress p").textContent;
const cleanAdress = fetchedAdress.replace(/<[^>]+>/g, ''); // Removes HTML tags
        // Geocode the address to get latitude and longitude
        var geocoder = new google.maps.Geocoder();
        var address = cleanAdress;
        
        geocoder.geocode({ 'address': address }, function(results, status) {
            if (status == 'OK') {
                var location = results[0].geometry.location;
                var map = new google.maps.Map(
                    document.getElementById('map'), { zoom: 15, center: location });
                var marker = new google.maps.Marker({ position: location, map: map });
            } else {
                console.log('Geocode was not successful for the following reason: ' + status);
            }
        });
    }
Anyone had similar issues with Google Maps & Joomla? How did you fix it?

I use the same script(s) on a static website, and it has no issues there.

Advertisement
User avatar
Per Yngve Berg
Joomla! Master
Joomla! Master
Posts: 31330
Joined: Mon Oct 27, 2008 9:27 pm
Location: Romerike, Norway

Re: Issues using Google Maps with Joomla?

Post by Per Yngve Berg » Sat May 11, 2024 5:54 am

Mod. Note: Relocated topic to the Coding Forum.

SharkyKZ
Joomla! Virtuoso
Joomla! Virtuoso
Posts: 3074
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: Issues using Google Maps with Joomla?

Post by SharkyKZ » Sat May 11, 2024 7:50 am

What code are you using to load the scripts?

SocketPup
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 134
Joined: Thu Mar 14, 2024 7:00 am

Re: Issues using Google Maps with Joomla?

Post by SocketPup » Sat May 11, 2024 12:40 pm

SharkyKZ wrote: Sat May 11, 2024 7:50 am What code are you using to load the scripts?
Index.php:

Code: Select all

$wa->useStyle('mystyle')
->useScript('callmapscript')
    ->useScript('myscript');
At the end:

Code: Select all

<jdoc:include type="scripts" />

SharkyKZ
Joomla! Virtuoso
Joomla! Virtuoso
Posts: 3074
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: Issues using Google Maps with Joomla?

Post by SharkyKZ » Tue May 14, 2024 12:07 pm

I can't reproduce the issue. But maybe myscript should be loaded before callmapscript? If so, you should make it a dependency of callmapscript.

SocketPup
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 134
Joined: Thu Mar 14, 2024 7:00 am

Re: Issues using Google Maps with Joomla?

Post by SocketPup » Wed May 15, 2024 7:24 am

SharkyKZ wrote: Tue May 14, 2024 12:07 pm I can't reproduce the issue. But maybe myscript should be loaded before callmapscript? If so, you should make it a dependency of callmapscript.
What I have done now is the following changes:

joomla.asset file:

Code: Select all

{
  "$schema": "https://developer.joomla.org/schemas/json-schema/web_assets.json",
  "name": "Gardentemplate",
  "version": "4.0.0",
  "description": "This file contains assets used by gardentemplate",
  "license": "GPL-2.0-or-later",
  "assets": [
    {
      "name": "mystyle",
      "type": "style",
      "uri": "style.css"
    },
    {
      "name": "myscript",
      "type": "script",
      "uri": "script.js",
	"attributes": {
        "async": true
      }
    }
  ]
}
script.js:

Code: Select all

const fetchedAdress = document.querySelector(".adress p").textContent;
const cleanAdress = fetchedAdress.replace(/<[^>]+>/g, ''); // Removes HTML tags
console.log(cleanAdress);

let map;
let geocoder;

async function initMap() {
    // Request needed libraries.
    //@ts-ignore
    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

    geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'address': cleanAdress }, function(results, status) {
      if (status == 'OK') {
      console.log(results);
      var location = results[0].geometry.location;
      const position = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() };
      
      var mapOptions = {
      zoom: 17,
      center: position,
      mapId: results[0].place_id,
      }
      
      // The map, centered at Uluru
      map = new Map(document.getElementById("map"), mapOptions);
      
      // The marker, positioned at Uluru
      const marker = new AdvancedMarkerElement({
      map: map,
      position: position,
      title: results[0].formatted_address,
      });
      } else {
      console.log('Geocode was not successful for the following reason: ' + status);
      }
      });
  }
  
  initMap();
index.php:

Code: Select all

$wa->useStyle('mystyle')
->useScript('myscript');
index.php at the end of document:

Code: Select all

<jdoc:include type="scripts" />

<script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
    key: "AIzaSyAVcByTo_57_zc2iqRvVlJauObFA9Sub5s",
    v: "weekly",
  })</script>
What happens is map seems to work, BUT if you reload the page, OR go to contact form or news category, the map isn't displayed, and I get the following error in console:
Uncaught SyntaxError: redeclaration of var map
<anonymous> http://localhost/blomstradgard/template ... s?9aa240:1
So variable map is being declared again despite already being declared once, is how I interpret it. Do I need to declare this variable elsewhere?

SocketPup
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 134
Joined: Thu Mar 14, 2024 7:00 am

Re: Issues using Google Maps with Joomla?

Post by SocketPup » Wed May 15, 2024 7:42 am

Addendum do my post above:

If I put all the google-map related js directly into index.php (without going through joomla.asset & $wa), I do not get the error. But I also understand this is not how you're supposed to add scripts in Joomla.
So how do I add my scripts the correct way, but without getting the error?

Advertisement

Post Reply

Return to “Joomla! 5.x Coding”