Skip to content

Shapefiles in OpenLayers

December 13, 2011

Update 2011-12-14: It seems that a lot of people are coming here from web searches with phrases like “shapefile openlayers.” If all you want to do is display your data in OpenLayers, I’d highly recommend using a program like Quantum GIS to convert your Shapefile to a more web-friendly format like KML or GeoJSON. Both of these formats can be read by OpenLayers directly, and you’ll see faster performance and more browser compatibility than if you were to load your Shapefiles directly.

Over the last few days, I’ve been using Tom Carden’s shapefile-js library that reads ESRI Shapefiles in JavaScript, which I found via a post on the Prodevelop blog. The library is quite incredible, but his samples use a simple canvas for display. I thought it would be really cool if this could be integrated with OpenLayers, so I created a bit of JavaScript to do so. You can give it a test drive here, and look at the code on GitHub.

Basically, the library does all the heavy lifting. My code converts the shapefile shapes to WKT, which is passed to OpenLayers. Ultimately, I’d like to see an OpenLayers plugin so that you can use Shapefiles directly (i.e., an OpenLayers.Format.Shapefile). The main issue I see is that there needs to be a new strategy as well as a new format, because a) Shapefiles are made up of multiple pieces and b) we need to use the BinaryAjax loader since Shapefiles are binary.

My code seems to work well with points, lines and polygons, including the donut polygon case (to see for yourself, look at South Africa). (I did not test the donut polygon case, but I think it should work). More eyes are of course welcome! Also, the shapefile-js library can only handle pretty small Shapefiles. If I integrate this into OpenLayers, I think, long term, using a Web Worker thread to parse the Shapefile would be wise (which is another challenge to direct OpenLayers integration).

EDIT 2011-12-13 22:36 -0800: I tested the donut polygon case.

  1. eko permalink
    May 15, 2012 2:21 am

    Hi, I’m newbie start learning open layer.. can open layer add layer from open street map ?

  2. ester permalink
    June 17, 2012 5:19 pm

    If GeoJSON can provide a faster performance, on what occasion would you think using this new plugin is preferable as compared to just converting it to GeoJSON?

  3. Matt Conway permalink*
    July 7, 2012 3:01 pm

    ester, in general it’s not. This is more of an exercise than anything anyone should be using in production. In a few years that could change with better binary file handling in-browser, but for now I’d consider it only a proof-of-concept.

Comments are closed.

%d bloggers like this: