0

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 :)

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to hear. Can you accept my answer (click the check mark beside it)? It's how we say thanks around here ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.