user3766432
user3766432

Reputation: 247

Google maps API javascript integration wordpress

I've been struggling to integrate the google maps api into a wordpress page and finally got it....sort of.

I added

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&sensor=true"> </script>

and

<body <?php if (is_page('Test5')) { echo 'onload="initialize()" onunload="GUnload()"'; } ?>> 

to header.php. I put them in the head section but outside of the existing php tags. BTW...the name of the page with the map is Test5.

From what I read, the second section of code should make it so the goggle maps javascript only loads on page 'Test5'. I added a dummy API key to the javascript URL to see if the script is loading on every page and sure enough it is. I get the invalid api key popup on every page.

Where did I go wrong?

Here is the code I added to the page ('Test5') using the "Text" tab. Just in case you need to see it.

<script>
  function initialize() {
    var map_canvas = document.getElementById('map_canvas');
    var map_options = {
      center: new google.maps.LatLng(44.5403, -78.5463),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(map_canvas, map_options)
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

I'm a noob when it comes to customizing wordpress and using google maps API so please make an explanations as noob friendly as possible :)

Upvotes: 0

Views: 262

Answers (1)

Hobo
Hobo

Reputation: 7611

You're including the Google JavaScript on every page, but only running it on the Test5 page. To only load it on Test5, add a check where you're enqueueing it, like this:

<?php if (is_page('Test5')) { ?>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&sensor=true"> </script>
<?php } ?>

A couple of other notes:

  • It's best to use wp_enqueue_script, rather than hardcoding it in header.php. It allows people who extend your code to replace it with a different version, if necessary, without changing your code
  • If I read this: google.maps.event.addDomListener(window, 'load', initialize); correctly, you're calling initialize on page load anyway - you shouldn't need the extra logic in the body tag (if you're sure you need GUnload you could probably do it in the same place - something like this answer)

Upvotes: 1

Related Questions