Cache Surprise

Post date: Nov 27, 2010 6:14:15 AM

Run this Geo-coding cache example from the browser.

It uses the Google Maps API.

Geo-coding Caches

"GClientGeocoder is equipped with a client-side cache by default. The cache stores geocoder responses, enabling faster responses if addresses are re-geocoded. You can turn off caching by passing null to the setCache() method of the GClientGeocoder object. However, we recommend that you leave caching on as it improves performance.

To change the cache being used by GClientGeocoder, call setCache() and pass in the new cache.

To empty the contents of the current cache, call the reset() method on the geocoder or on the cache directly. Developers are encouraged to build their own client-side caches.

In this example, we construct a cache that contains pre-computed geocoder responses to six capital cities in countries covered by the geocoding API. First, we

    1. build an array of geocode responses

    2. create a custom cache that extends a standard GeocodeCache

    3. once the cache is defined, we call the setCache() method. There is no strict checking of objects stored in the cache, so you may store other information (such as population size) in the cache as well."

// Build an array of geocode responses for the 6 capitals

var city = [ { name: "Washington, DC", Status: { code: 200, request: "geocode" }, Placemark: [ { address: "Washington, DC, USA", population: "0.563M", AddressDetails: { Country: { CountryNameCode: "US", AdministrativeArea: { AdministrativeAreaName: "DC", Locality: { LocalityName: "Washington" } } }, Accuracy: 4 }, Point: { coordinates: [-77.036667, 38.895000, 0] } } ] }, ... ]; // etc., and so on for other cities

var map;

var geocoder;

// CapitalCitiesCache is a custom cache that extends the standard GeocodeCache. // We call apply(this) to invoke the parent's class constructor.

function CapitalCitiesCache() { GGeocodeCache.apply(this); }

// Assigns an instance of the parent class as a prototype of the child class,

// to make sure that all methods defined on the parent class can be directly

// invoked on the child class.

CapitalCitiesCache.prototype = new GGeocodeCache();

// Override the reset method to populate the empty cache with information from

// our array of geocode responses for capitals. CapitalCitiesCache.prototype.reset = function() {GGeocodeCache.prototype.reset.call(this); for (var i in city) { this.put(city[i].name, city[i]); } }

map = new GMap2(document.getElementById("map_canvas"));

map.setCenter(new GLatLng(37.441944, -122.141944), 6);

// Here we set the cache to use the UsCitiesCache custom cache.

geocoder = new GClientGeocoder();

geocoder.setCache(new CapitalCitiesCache());