Tag Archive for 'MassGIS'

Re-projecting vectors in JavaScript

I know, it eventually all boils down to maths. But it still blows my mind that you can re-project geographic features on-the-fly with a few lines of JavaScript in a web browser.

How?

There is this great library PROJ.4, that does everything you’d ever want in terms of cartographic projections. A few smart people have ported PROJ.4 to JavaScript, called Proj4js then.

Proj4js works great in combination with OpenLayers, a popular JavaScript web mapping framework, and allows on-the-fly projections between any spatial reference systems browser applications.

<script src="proj4js-compressed.js"></script>
<script src="http://openlayers.org/api/OpenLayers.js"></script>

Define the spatial reference you’re planning to use. Check Spatial Reference for the exact projection parameters and include them in your code.

Proj4js.defs["EPSG:26986"] = "+title=Massachusetts Mainland NAD83 +proj=lcc +lat_1=42.68333333333333 +lat_2=41.71666666666667 +lat_0=41 +lon_0=-71.5 +x_0=200000 +y_0=750000 +ellps=GRS80 +datum=NAD83 +units=m +no_defs";

Adding all desired projections to the OpenLayers script…

projOSM = new OpenLayers.Projection("EPSG:900913");
projWGS84 = new OpenLayers.Projection("EPSG:4326");
projMassGIS = new OpenLayers.Projection("EPSG:26986");

map = new OpenLayers.Map ("map", {
	maxExtent: new OpenLayers.Bounds( -20037508.34, -20037508.34, 20037508.34, 20037508.34),
	maxResolution: 156543.0399,
	units: 'm',
	projection: projOSM,
	displayProjection: projWGS84,
	allOverlays: false
});

osm = new OpenLayers.Layer.OSM(
	"OpenStreetMap",
       "http://tile.openstreetmap.org/${z}/${x}/${y}.png"
);

openspace = new OpenLayers.Layer.WFS("Open space", "http://giswebservices.massgis.state.ma.us/geoserver/wfs", {
	typename: "massgis:GISDATA.OPENSPACE_POLY"
}, {
	projection: projMassGIS
	attribution: "<a href='http://www.mass.gov/mgis/'>MassGIS</a>"
});

…results in an interactive map with MassGIS Open Space WFS vector features overlayed on an OpenStreetMap base layer, using WGS84 lat/lon as display coordinates.

On a sidenote: OpenLayers comes with a Python proxy to retrieve information from remote servers via an XMLHttpRequest. Here is a good how-to get Python play well with IIS 6 on Windows Server 2003, which was quite useful.

Don’t forget to add the domains you’re trying to access to the Python proxy. For MassGIS you would add following string for instance:

allowedHosts = ['giswebservices.massgis.state.ma.us']