Instantly share code, notes, and snippets.

Embed
What would you like to do?
Making maps 101 - a few things I've picked up
cd [directory where your shapefiles]
shapeindex *.shp
for i in *.shp
> zip `basname $i .shp` `basename $i shp`*;
var geojson, map;
$(document).ready(function(){
var spin_opts = {
lines: 12,
length: 7,
width: 4,
radius: 10,
color: '#fff',
speed: 1,
trail: 60,
shadow: true
};
var target = document.getElementById('spinner');
var spinner = new Spinner(spin_opts).spin(target);
var streets = new L.TileLayer('http://{s}.tile.cloudmade.com/[My API key]/998/256/{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.fitBounds(bbox);
$.getJSON('{% url complex-counties %}', function(data){
spinner.stop();
parse_map_data(data);
});
});
function parse_map_data(data){
$.each(data, function(key,val){
geojson = new L.GeoJSON();
geojson.on('featureparse', function(e){
e.layer.on('click', function(e){
shape_click(this);
}, e.properties);
});
geojson.addGeoJSON(val);
map.addLayer(geojson);
});
}
function shape_click(shape){
var content = "<h3>" + shape['name'] + "</h3>";
var popup = new L.Popup();
var point = new L.LatLng(shape['center'][1],shape['center'][0]);
popup.setLatLng(point);
popup.setContent(content);
var bb = shape['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);
}
#!/usr/bin/env python
# For this script to work you must set the Django settings file
# as an environment setting before importing LayerMapping
# Alternatively you can place
# export DJANGO_SETTINGS_MODULE=settings
# in your .bash_profile
# or paste this code into a $ manage.py shell
import sys
import site
import os
vepath = '/home/web/sites/demo/lib/python2.7/site-packages' # adjust for your env
prev_sys_path = list(sys.path)
# add the site-packages of our virtualenv as a site dir
site.addsitedir(vepath)
sys.path.append('/home/web/sites/demo/map_demo') # adjust this, too
sys.path.append('/home/web/sites/demo/') # and this
new_sys_path = [p for p in sys.path if p not in prev_sys_path]
for item in new_sys_path:
sys.path.remove(item)
sys.path[:0] = new_sys_path
os.environ['DJANGO_SETTINGS_MODULE'] = 'map_demo.settings' # put your settings info here
from psycopg2 import IntegrityError
from django.contrib.gis.utils import mapping, LayerMapping, add_postgis_srs
from map_demo.california.models import County, Place # put your models here
try:
add_postgis_srs(900913)
except IntegrityError:
print "The Google Spherical Mercator projection, or a projection with srid 900913, already exists, skipping insert"
# Adjust to find your data files
County_shp = '/home/web/sites/demo/data/county/tl_2010_06_county10.shp'
Place_shp = '/home/web/sites/demo/data/place/tl_2010_06_place10.shp'
County_mapping = {
'state_fips' : 'STATEFP10',
'county_fips' : 'COUNTYFP10',
'county_ansi' : 'COUNTYNS10',
'geo_id' : 'GEOID10',
'name' : 'NAME10',
'name_trans' : 'NAMELSAD10',
'mpoly' : 'MULTIPOLYGON',
}
Place_mapping = {
'state_fips' : 'STATEFP10',
'place_fips' : 'PLACEFP10',
'place_ansi' : 'PLACENS10',
'geo_id' : 'GEOID10',
'name' : 'NAME10',
'name_trans' : 'NAMELSAD10',
'mpoly' : 'MULTIPOLYGON',
}
County_layer = LayerMapping(County,
County_shp,
County_mapping,
transform=False,
encoding='iso-8859-1')
County_layer.save(verbose=True, strict=True, progress=True)
Place_layer = LayerMapping(Place,
Place_shp,
Place_mapping,
transform=False,
encoding='iso-8859-1')
Place_layer.save(verbose=True, strict=True, progress=True)
from django.contrib.gis.db import models
class County(models.Model):
state_fips = models.CharField(max_length=10)
county_fips = models.CharField(max_length=10)
county_ansi = models.CharField(max_length=10)
geo_id = models.CharField(max_length=10)
name = models.CharField(max_length=100)
name_trans = models.CharField(max_length=100)
mpoly = models.MultiPolygonField()
objects = models.GeoManager()
def __unicode__(self):
return self.name
class Place(models.Model):
state_fips = models.CharField(max_length=10)
place_fips = models.CharField(max_length=10)
place_ansi = models.CharField(max_length=10)
geo_id = models.CharField(max_length=10)
name = models.CharField(max_length=100)
name_trans = models.CharField(max_length=100)
mpoly = models.MultiPolygonField()
objects = models.GeoManager()
def __unicode__(self):
return self.name
def complex_counties(request):
counties = County.objects.all()
bbox = json.dumps(counties.extent())
if request.is_ajax():
d = {}
for county in counties.geojson():
geojson = json.loads(county.geojson)
properties = {'name': county.name_trans, 'bbox':county.mpoly.extent, 'center':county.mpoly.point_on_surface.coords}
geojson['id'] = county.geo_id
geojson['properties'] = properties
d[county.geo_id] = geojson
return HttpResponse(json.dumps(d), mimetype='application/json')
else:
return render_to_response('complex-county.html', { 'bbox': bbox }, context_instance=RequestContext(request))
var map, vector, wkt, features, options, geom;
var collect = [];
var f = [];
var src = new OpenLayers.Projection('EPSG:4326');
var dest = new OpenLayers.Projection('EPSG:900913');
window.onload = function(){
options = {
'projection' : new OpenLayers.Projection("EPSG:900913"),
'numZoomLevels' : 20,
'displayProjection' : new OpenLayers.Projection("EPSG:4326"),
'units' : "m",
'maxResolution' : 156543.0339,
'maxExtent' : new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508)
};
map = new OpenLayers.Map('map', options);
layer = new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)");
map.addLayer(layer);
map.setCenter(
new OpenLayers.LonLat(-97, 38).transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
),
5
);
vector = new OpenLayers.Layer.Vector("Regions");
wkt = new OpenLayers.Format.WKT();
{% for county in counties %}
features = wkt.read('{{ county.mpoly }}');
geom = features.geometry.transform(src, dest);
collect.push(geom);
var feat = new OpenLayers.Feature.Vector(geom);
f.push(feat);
{% endfor %}
vector.addFeatures(f);
map.addLayer(vector);
};
#counties {
polygon-opacity: 0;
line-width: 2;
line-color: #123456;
line-opacity: 0.4;
line-join: round;
}
apt-get install python-software-properties
add-apt-repository ppa:developmentseed/mapbox
apt-get update
apt-get install libmapnik2-dev
apt-get install python-mapnik2
cd /home/tiles/
apt-get install python-virtualenv
virtualenv .
source bin/activate
cd tilestache/
pip install -r requirements.txt
apt-get install nginx
vi /etc/nginx/sites-enabled/tiles # added a reverse proxy for the app to serve it to my host box
invoke-rc.d nginx restart
gunicorn "TileStache:WSGITileServer('configs/demo.cfg')"
from django.conf.urls.defaults import *
from california.views import *
urlpatterns = patterns('',
url(r'^counties/$', counties, name='counties'),
url(r'^places/$', places, name='places'),
)
from django.shortcuts import render_to_response
from california.models import *
def counties(request):
counties = County.objects.all()
return render_to_response('basic-county.html', {'counties': counties}, context_instance=RequestContext(request))
def places(request):
places = Place.objects.all()
return render_to_response('basic-place.html', {'places': places}, context_instance=RequestContext(request))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment