Contacts

Link Addresses to Google Maps with JQuery (Part 1)

First, you need JQuery. I'm not going to go into the basics of JQuery, but you should be using it.

Second, We use this to create a global class, usable throughout the website to signify an address, and provide links to Google Maps. The stripHTML function is only required if you wish to markup your addresses for formatting. From then on, you just do a

  1. <span class="address">1600 Amphitheatre Parkway<br />Mountain View, CA 94043

Now for the code:

  1. function stripHTML(oldString) {
  2.    var newString = "";
  3.    var inTag = false;
  4.    for(var i = 0; i < oldString.length; i++) {
  5.         if(oldString.charAt(i) == '<') inTag = true;
  6.         if(oldString.charAt(i) == '>') {
  7.               inTag = false;
  8.               i++;
  9.         }
  10.         if(!inTag) newString += oldString.charAt(i);
  11.          }
  12.    return newString;
  13. }
  14.  
  15.  
  16. /* <span class="address">Address</span> will auto create link to Google Maps */
  17. $(function() {
  18.         $(".address").each(
  19.                 function() {
  20.                         var address = this.innerHTML
  21.                         this.innerHTML = '<a href="http://maps.google.com/maps?q=' + stripHTML(address) + 'class="map">' + address + '</a>';
  22.                 }
  23.         );
  24. });

Keep in mind, we only want to wrap the address inside the tags.

In part 2, we'll use JQuery with Google Maps to allow the user to view the map on the website, or jump off to Google Maps.

Filed under: