geocode cache
Once an address is geocoded, it is cached in local storage and not geocoded again.
by ryanttb
HTML
<script src="http://code.jquerygeo.com/jquery.geo-1.0.0-b1.5.min.js"></script>
<form id="geocode">
<label>
<span>Location</span>
<input id="l" type="text" name="l" />
</label>
<button type="submit">Locate</button>
</form>
<div>
Coords: <span id="coords"></span>
</div>
<div>
Status: <span id="status"></span>
</div>
<div id="map"></div>
CSS
#map {
width: 320px;
height: 240px;
outline: solid 1px #222;
}
JavaScript
var cacheString = localStorage.getItem("cache") || "{}";
var cache = JSON.parse(cacheString);
var coords;
$("#geocode").submit(function() {
var l = $("#l").val().toUpperCase();
$("#coords,#status").text("");
if (cache[l]) {
$("#coords").text(cache[l].join(", "));
map.geomap("option", "center", cache[l]);
$("#status").text("from cache");
} else {
$.ajax({
url: "http://open.mapquestapi.com/nominatim/v1/search",
data: {
format: "json",
q: l
},
dataType: "jsonp",
jsonp: "json_callback",
success: function (results) {
if (results && results.length > 0) {
// if found, grab the location's lon & lat
if (results[0].lon && results[0].lat) {
coords = [
results[0].lon,
results[0].lat
];
$("#coords").text( coords.join(", ") );
map.geomap("option", "center", coords);
$("#status").text("geocoded");
cache[l] = coords;
localStorage.setItem("cache", JSON.stringify(cache));
} else {
$("#status").text("result doesn't have coords");
}
} else {
$("#status").text("no results");
}
}
});
}
return false;
});
var map = $("#map").geomap({zoom: 8});