Embedded Google Map Management

Adding a map to a webpage these days is as easy as embedding a little code and JavaScript on your site. But what about when you want to change the location of the map? This HowTo shows you one way that you can use MagicEdit along with Google Maps to embed a map that is easily updated by the content manager just by typing in a new address.

We've used this script (or something very like it) for things like real estate listings. Each page gets a map, and the content manager just updates the address and the map re-centers on the address automatically.

So, how is it done?

First of all, we start off with some basic MagicEdit regions with plain text editing:

<span id="street">
  <magicedit me_plain me_name="street">1600 Pennsylvania Ave NW</magicedit>
</span><br />                                                
<span id="cityStateZip">
  <magicedit me_plain me_name="cityStateZip">Washington, DC 20500 </magicedit>

<div style="height:300px; width:400px" id="map_canvas"></div> 

We're wrapping the editable address regions with spans so the JavaScript we are going to use will be able to bind to the appropriate parts of the address.

The div with id="map_canvas" is where the map will be appearing. The next thing we need to do is add the JavaScript to both create the map element and then center and add a marker based on our address. It utilizes the Google Maps API, as well as a JavaScript function that initializes the map based on the current address. Download the "me_map.js" file (see below) and put it up on your site, then add the following two lines to the head of your page:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/me_map.js"></script>

Make sure the path is correct to the location of the "me_map.js" file.

Finally, we need to call the map initialization function when the page loads. Update the body tag of your site to match this:

<body onLoad="initializeMap();">

If you are using jQuery and want to avoid putting scripting in the code, just call initializeMap() inside your $(document).ready() function.

The Results

Now when you log into the site you will see a couple of edit buttons by the address, as well as a map that should be centered on the address entered (the White House, in this case).

Now I can click on the little edit buttons and update the address! Here is what I get after entering Apple's address in Cupertino, then logging out. Sure enough, the map has updated its location accordingly.

So that's all you need to do to add a dynamically updatable map to your MagicEdit site.