I have a shape file, and I want to show it on the web by using leaflet (http://leaflet.cloudmade.com/). Since leaflet only support geoJSON, I should change the shp file into geoJSON. It is easy since I can use “save as” capability in Quantum-GIS.
Although I can use geojson as database (by reading, edit and writing the file programmatically), I think it is better to use the “real” database. My-SQL is the most popular one, and it support spatial data, so I decide to use MySQL.
The scenario is:
- Change shp into MySQL (I use ogr2ogr and just simply run this command: ogr2ogr -f “MySQL” MySQL:”geo,user=root,host=localhost,password=toor” -lco engine=MYISAM airports.shp)
- Fetch MySQL database into geojson <– here is the problem
- Using ajax to get the geojson and change the layout <– this should be easy, I’m good with JQuery
There is a column in My MySQL table which its type is “GEOMETRY”, Look the table definition below:
CREATE TABLE IF NOT EXISTS `airports` (
`OGR_FID` int(11) NOT NULL AUTO_INCREMENT,
`SHAPE` geometry NOT NULL,
`cat` decimal(10,0) DEFAULT NULL,
`na3` varchar(80) DEFAULT NULL,
`elev` double(32,3) DEFAULT NULL,
`f_code` varchar(80) DEFAULT NULL,
`iko` varchar(80) DEFAULT NULL,
`name` varchar(80) DEFAULT NULL,
`use` varchar(80) DEFAULT NULL,
UNIQUE KEY `OGR_FID` (`OGR_FID`),
SPATIAL KEY `SHAPE` (`SHAPE`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=77 ;
Is there any way to change such a table into geojson format?
(I prefer the easy way, but if there is not, just change the column into array like is acceptable)
EDIT:
I use geophp written by phayes.
https://github.com/phayes/geoPHP/wiki/Example-format-converter.
This solves the main problem. Only need to a bit mess up with adding feature etc.
Any easier solution?
While there may not be a direct method to convert from a mysql spatial entity to geojson, you can try the following:
Note that just calling jsonEncode() on the entity, as others have suggested, will not yeild geoJson.
My personal suggestion, which does not directly answer your question, would be to store the data in the format you need it retrieved in. It will reduce the overhead required to process the data every time you need it.
The easiest way to do this is to store the geojson in plain text as you suggested. If, for whatever reason, you also need the geometry stored in native format, you can store it in another column. The only downside is keeping the two columns in sync.