In my previous posts on using the Google Map API, I did not address how slow the geo-coding (converting addresses to latitude and longitude) process is.  I wanted to find some method of  caching the data for a reasonable period of time so that the map loads quickly but I still can get address changes in a timely manner.

Since I am using WordPress, this led me to transients.  I added my transient function to the after_setup_theme hook, which runs  before the init hook since I wanted to cache the data as soon as possible. Here is the code I used in functions.php:

add_action( 'after_setup_theme', 'rotary_setup' );

if ( ! function_exists( 'rotary_setup' ) ):
function rotary_setup() {
$markers = array();
$markerRow = 0;
if (false === ($value = get_transient('map_data'))) {
$rotaryclubs = simplexml_load_file('http://www.ismyrotaryclub.org/club/Clubmeetings.cfm?D=5030&ClubTypeIDs=0,4&xsl=http://rotary5030.org/xsl/MeetingsX.xsl');
foreach($rotaryclubs->CLUB as $club) {
if (strlen (strval($club->MEETINGADDRESS)) >0 ) {
$address = urlencode($club->MEETINGADDRESS . ' ' . $club->MEETINGCITY . ' ' . $club->MEETINGSTATECODE . ' ' . $club->MEETINGPOSTALCODE);
$geocode = simplexml_load_file('http://maps.googleapis.com/maps/api/geocode/xml?address=' . $address . '&sensor=false');
$markers[$markerRow] = array("clubname"=>strval($club->CLUBNAME), "address"=>strval($geocode->result->formatted_address),"lat"=>strval($geocode->result->geometry->location->lat), "lng"=>strval($geocode->result->geometry->location->lng));
$markerRow++;
}
}
set_transient('map_data', json_encode($markers), 60*60*12);
}
}
endif;

 

Notice a few things about this code:

  1. It is basically the same method of pulling XML data and creating JSON outpu
  2. The transient data expires in 12 hours
  3. We check to see if the transient data exists before running the code.

To use this code to build the map I added the following to my header.php:

<script type="text/javascript">
var data = <?php echo get_transient('map_data'); ?>;
</script>

Then my initialize() javascript function no longer needs to call getJSON as I already have the data. The new function looks like this:

function initialize() {
if (jQuery("#map_canvas").length > 0) {
var latlng = new google.maps.LatLng(47.6062095, -122.3320708);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); for (i=0; i
addMarker(data[i].lat, data[i].lng, data[i].clubname, data[i].address)
}
}
}

You can view the results of the geo-coding on this website.