Skip to content

Instantly share code, notes, and snippets.

@evz
Created March 8, 2012 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evz/2001692 to your computer and use it in GitHub Desktop.
Save evz/2001692 to your computer and use it in GitHub Desktop.
Making maps 101 - a few things I've picked up, part 2
var census_data = {};
$(document).ready(function(){
//...(snip)...
});
function parse_results(resp){
//...(skip a bit)...
if (resp['status'] != 'OK'){
//...(snip)...
} else {
//...(snip)...
$.each(county_geo, function(key,val){
fetch_data(val['id'], census);
counties += '<p id="' + val['id'] + '" class="result county">' + val['properties']['name'] + '</p>';
});
$.each(place_geo, function(key,val){
fetch_data(val['id'], census);
places += '<p id="' + val['id'] + '" class="result place">' + val['properties']['name'] + '</p>';
});
// ...(snip)...
}
}
function fetch_data(geoid, handler){
var callback = 'geoid_' + geoid;
var url = 'http://censusdata.ire.org/' + geoid.substr(0,2) + '/' + geoid + '.jsonp';
$.ajax(url,{
dataType: "jsonp",
jsonpCallback: callback,
success: census
})
}
function census(data){
census_data[data['geoid']] = data;
}
function zoom_detail(id, cl){
//...(snip)...
$.each(geo, function(key, val){
//...(snip)
var content = '<h3>'+val['properties']['name']+'</h3>';
content += "<p>The 2010 population of "+ census_data[val['id']]['metadata']['NAME'] + " was " + census_data[val['id']]['data']['2010']['P1']['P001001'] + ".</p>";
//...(snip)...
}
}
var county_geo, place_geo, map, geojson, counties, places;
$(document).ready(function(){
var streets = new L.TileLayer('http://{s}.tile.cloudmade.com/bcf2471ca35f48a6a4e28a704ba64c9c/998/256/{z}/{x}/{y}.png');
counties = new L.TileLayer('http://tiles/counties/{z}/{x}/{y}.png');
places = new L.TileLayer('http://tiles/places/{z}/{x}/{y}.png');
var bb = {{ bbox }};
var sw = new L.LatLng(bb[1], bb[0], true);
var ne = new L.LatLng(bb[3], bb[2], true);
var bbox = new L.LatLngBounds(sw,ne);
map = new L.Map('map');
map.addLayer(streets);
map.addLayer(counties);
map.addLayer(places);
map.fitBounds(bbox);
$('#map-search').submit(function(){
var url = '{% url map-search %}';
var options = {
url: url,
success: parse_results,
resetForm: false
};
$(this).ajaxSubmit(options);
return false;
});
$('.result').live('click', function(){
var cl = $(this).attr('class').split(' ');
if (search_array(cl,'clarify')){
zoom_detail($(this).attr('id'), cl[1]);
}
});
$('.clarify').live('click', function(){
var params = {'search': $(this).text()}
$.getJSON('{% url map-search %}', params, function(data){
parse_results(data);
});
});
$('.layer-picker').click(function(){
var selected = $(this).val();
if ($(this).is(':checked')){
map.addLayer(eval(selected));
} else {
map.removeLayer(eval(selected));
}
});
});
function parse_results(resp){
$('#counties').children().remove();
$('#places').children().remove();
$('#errors').children().remove();
if (resp['status'] != 'OK'){
var info = '<p>' + resp['message'] + '</p>';
if (resp['status'] == 'MULTIPLE_MATCHES') {
$.each(resp['clarify'], function(key,val){
info += '<p class="result clarify">' + val + '</p>';
});
}
$('#errors').append(info);
} else {
county_geo = resp['counties'];
place_geo = resp['places'];
var counties = '<h3>County results</h3>'
var places = '<h3>Place results</h3>'
$.each(county_geo, function(key,val){
counties += '<p id="' + val['id'] + '" class="result county">' + val['properties']['name'] + '</p>';
});
$.each(place_geo, function(key,val){
places += '<p id="' + val['id'] + '" class="result place">' + val['properties']['name'] + '</p>';
});
$('#counties').append(counties);
$('#places').append(places);
}
}
function zoom_detail(id, cl){
var geo;
if (cl == 'place'){
geo = place_geo;
} else if (cl == 'county'){
geo = county_geo;
}
$.each(geo, function(key, val){
if (val['id'] == id){
if (geojson){
map.removeLayer(geojson);
}
geojson = new L.GeoJSON();
var content = '<h3>'+val['properties']['name']+'</h3>';
var popup = new L.Popup();
var point = new L.LatLng(val['properties']['center'][1],val['properties']['center'][0]);
popup.setLatLng(point);
popup.setContent(content);
geojson.addGeoJSON(val);
map.addLayer(geojson);
var bb = val['properties']['bbox'];
var sw = new L.LatLng(bb[1], bb[0], true);
var ne = new L.LatLng(bb[3], bb[2], true);
var bbox = new L.LatLngBounds(sw,ne);
map.fitBounds(bbox);
map.openPopup(popup);
}
});
}
function search_array(arr, obj){
return (arr.indexOf(obj) == -1);
}
$(document).ready(function(){
var streets = new L.TileLayer('http://{s}.tile.cloudmade.com/[My API key]/998/256/{z}/{x}/{y}.png');
var counties = new L.TileLayer('http://tiles/counties/{z}/{x}/{y}.png');
var places = new L.TileLayer('http://tiles/places/{z}/{x}/{y}.png');
var bb = {{ bbox }};
var sw = new L.LatLng(bb[1], bb[0], true);
var ne = new L.LatLng(bb[3], bb[2], true);
var bbox = new L.LatLngBounds(sw,ne);
var map = new L.Map('map');
map.addLayer(streets);
map.addLayer(counties);
map.addLayer(places);
map.fitBounds(bbox);
});
def map_search(request):
counties = County.objects.all()
places = Place.objects.all()
bbox = json.dumps(counties.extent())
if request.is_ajax():
q = request.GET['search']
goog = 'http://maps.googleapis.com/maps/api/geocode/json'
r = requests.get(goog, params={'address': q, 'sensor': 'false'});
resp = json.loads(r.content)
d = {'status': resp['status']}
if resp['status'] != 'OK':
d['message'] = 'Nothing was found matching your search. Please try again.'
elif len(resp['results']) > 1:
clarify = []
for res in resp['results']:
clarify.append(res['formatted_address'])
d['status'] = 'MULTIPLE_MATCHES'
d['message'] = 'Did you mean one of these? Click the one you wanted to resubmit.'
d['clarify'] = clarify
else:
bounds = resp['results'][0]['geometry']['viewport']
bbox = (bounds['southwest']['lng'], bounds['southwest']['lat'], bounds['northeast']['lng'], bounds['northeast']['lat'])
bbox_poly = Polygon.from_bbox(bbox)
cnts = counties.filter(mpoly__bboverlaps=bbox_poly)
plcs = places.filter(mpoly__bboverlaps=bbox_poly)
c = []
p = []
for cnt in cnts.geojson():
geojson = json.loads(cnt.geojson)
geojson['properties'] = {
'name': cnt.name_trans,
'bbox': cnt.mpoly.extent,
'center':cnt.mpoly.point_on_surface.coords
}
geojson['id'] = cnt.geo_id
c.append(geojson)
d['counties'] = c
for plc in plcs.geojson():
geojson = json.loads(plc.geojson)
geojson['properties'] = {
'name': plc.name_trans,
'bbox': plc.mpoly.extent,
'center':plc.mpoly.point_on_surface.coords
}
geojson['id'] = plc.geo_id
p.append(geojson)
d['places'] = p
return HttpResponse(json.dumps(d), mimetype='application/json')
else:
return render_to_response('map-search.html', { 'bbox': bbox }, context_instance=RequestContext(request))
{
"cache":
{
"name": "Disk",
"path": "/home/tiles/stache",
"umask": "0000",
"dirs": "portable",
},
"layers":
{
"counties":
{
"provider": {"name": "mapnik", "mapfile": "../styles/counties.xml"},
"projection": "spherical mercator"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment