geocodarium
Geocode one property in an array of objects to another.
by ryanttb
HTML
<script src="http://code.jquerygeo.com/jquery.geo-1.0.0-b1.5.min.js"></script>
<label for="source" class="json">Source data</label>
<textarea id="source" name="source"></textarea>
<label><span>Location field (input)</span> <input type="text" id="loc-field" value="country" /></label>
<label><span>Center field (output)</span> <input type="text" id="center-field" value="coordinates" /></label>
<label><span>Country code field (output)</span> <input type="text" id="country-field" value="countryCode" /></label>
<button type="button">Geocode</button>
<label for="dest" class="json">Output</label>
<textarea id="dest" name="dest"></textarea>
<div id="map"></div>
CSS
button, label {
display: block;
}
label span {
display: inline-block;
width: 12em;
}
textarea {
width: 80%;
height: 10em;
}
#map {
width: 256px;
height: 256px;
outline: solid 1px #222;
}
JavaScript
$("button").click(function() {
$("#dest").val("");
var source;
var countries;
var searchPoint = {
type: "Point",
coordinates: [0,0]
};
var locField = $("#loc-field").val();
var centerField = $("#center-field").val();
var countryField = $("#country-field").val();
try {
source = JSON.parse($("#source").val());
} catch (e) { }
if (!source || !$.isArray(source)) {
$("#dest").val("source is not a JSON array");
} else if (!locField || !centerField || !countryField) {
$("#dest").val("all input and output fields are required");
} else {
for (var i = 0; i < source.length; i++) {
source[i][centerField] = geocode(source[i][locField].toUpperCase());
source[i][countryField] = null;
if (source[i][centerField]) {
// get country code from map
searchPoint.coordinates[0] = source[i][centerField][0];
searchPoint.coordinates[1] = source[i][centerField][1];
countries = map.geomap("find", searchPoint, 2);
if (countries.length > 0) {
source[i][countryField] = countries[0].id;
}
}
}
$("#dest").val(JSON.stringify(source));
}
});
function geocode(l) {
if (l && cache[l] && $.isArray(cache[l])) {
return cache[l];
} else {
// previously an error
return null;
}
}
var map = $("#map").geomap({
zoom: 18,
services: [],
shapeStyle: {
color: "#444",
stroke: "#fff",
strokeWidth: "2px"
}
});
// grab the world countires file
$.getJSON("http://data.jquerygeo.com/world-countries.json", function (result) {
// blast it onto the map
map.geomap("append", result);
});
var cacheDefault =...