Saturday, February 2, 2008

Reading Local Shapefiles

ESRI shapefiles are fairly ubiquitous. That is why I keep getting requests like this “Hey, I would like to render my local shapefiles on top the AWX map, can I do that ?” And I reply “Sure...but !” - Remember the security sandbox of the flash player; 1 - you can only communicate with the server that hosts the swf, or with a host that has a crossdomain.xml file, and 2 - there is no way that you can access your local disk drive directly - So, let’s turn these two restrictions into assets :-) I’m luck enough to run on a Mac, which comes with Apache Web Server built in. So, if I place a crossdomain.xml file at the base url of my local server, then I can access my local shapefiles. Cool eh ? Next, found this AS3 library that can read the shp and dbf file given a ByteArray instance. Here is a code snippet that I used on a project to overlay the continents shapes on top of the map.

private function onCreationComplete( event : FlexEvent ) : void
var urlStream : URLStream = new URLStream();
function( event : Event ) : void
var byteArray : ByteArray = new ByteArray();
urlStream.readBytes( byteArray, 0.0, urlStream.bytesAvailable);

var style : IStyle = new PolygonStyle( 0xCCCCCC, 0.25, 1, 0x0 );

var shpHeader : ShpHeader = new ShpHeader( byteArray);
while( byteArray.position < byteArray.length)
var shpRecord : ShpRecord = new ShpRecord( byteArray );
var shpPolygon : ShpPolygon = shpRecord.shape as ShpPolygon;
for each ( var arr : Array in shpPolygon.rings)
var coords : Array = [];
for each ( var sp : ShpPoint in arr )
coords.push( new GeoPoint( sp.x, sp.y));
var polygon : Polygon = new Polygon( new PolygonShape( coords), style);
polygonLayer.addOverlay( polygon );
, false, 0.0, true);
urlStream.load( new URLRequest("shapefiles/continents3.shp"));

No comments: