Home » Wordpress » How to initialize Google Maps in the body tag?

How to initialize Google Maps in the body tag?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I am implementing Google Maps in one of my pages. I know I need to add onload="initialize()" onunload="GUnload()" within the <body> tag but I am not sure how.

Currently within my page I have pasted the following:

<body onload="initialize()" onunload="GUnload()">
  <p>To Add your Google Map you must first plot your address by searching</p>
  <p>
    <input id="address" type="textbox" value="" placeholder="Search For Your Address">
    <input type="button" value="Plot Your Address" onclick="codeAddress()">
  </p>
  <div id="map_canvas" style="width: 770px; height: 270px; border: 5px solid #EDEDED">
  </div>
</body>

Even though this actually works, it must be terrible mark-up as it is a body section within a body section for the main page.

I am using WordPress but I’m not sure if the above markup is OK or whether I should be putting it in the main page body tag. The problem is that I am not sure how to do this if needed. As I only need it on one page and not my entire site, I don’t want to add this to the site’s body tag to initialize Google Maps on every page and slow the site down.

Thanks for any advice.

Answers:

No you don’t want to be adding another body tag into the specific page template that uses the map. Your opening <body> tag will be in header.php , you should get the page ID of the specific page which you want to load it on and do;

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

in header.php

Which will add that code to (in my instance) page 374.

To find the page id, just hover over it in the Pages section in the backend and you can see the ID in the link url.

For multiple pages you would use;

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

and you can also use the slug or title instead of ID, but of course they are easy for your client to change and stop that code working. Here’s the codex link on is_page;

http://codex.wordpress.org/Function_Reference/is_page

Leave a Reply

Your email address will not be published. Required fields are marked *