What is Geojson

According to wikipedia, GeoJSON is an open standard format designed for representing simple geographical features, along with their non-spatial attributes, based on JavaScript Object Notation.

Simply, Geojson is a JavaScript friendly geo-related data format, which uauslly contain points, polylines, polygons and other properties.It’s easy to to make visualization on webpage. There are so many packages supply API for geojson, Leaflet, MapBox, and etc. And of course you can easily parse it with jQuery.

Geojson is stick on its format. There’s websites where you can check the format.Here’s an example from offical website.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [102.0, 0.5]
},
"properties": {
"prop0": "value0"
}
}, {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[102.0, 0.0],
[103.0, 1.0],
[104.0, 0.0],
[105.0, 1.0]
]
},
"properties": {
"prop0": "value0",
"prop1": 0.0
}
}, {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[100.0, 0.0],
[101.0, 0.0],
[101.0, 1.0],
[100.0, 1.0],
[100.0, 0.0]
]
]
},
"properties": {
"prop0": "value0",
"prop1": {
"this": "that"
}
}
}]
}

Convertation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import csv

# Read in raw data from csv
rawData = csv.reader(open('filename.csv', 'rb'), dialect='excel')


# the template. where data from the csv will be formatted to geojson
template = \
''' \
{ "type" : "Feature",
"geometry" : {
"type" : "Point",
"coordinates" : [%s, %s]},
"properties" : { "id" : %s, "unixTime" : "%s", "msgtext" : "%s", "userID": "%s"}
},
'''


# the head of the geojson file
output = \
''' \

{ "type" : "Feature Collection",
"features" : [
'''


# loop through the csv by row skipping the first
iter = 0
for row in rawData:
# iter += 1
# if iter >= 2:
id = row[2]
lat = row[5]
lon = row[6]
unixTime = row[1]
msgtext = row[3]
userID = row[4]
# output += template % (row[0], row[2], row[1], row[3], row[4])
output += template % (lon, lat, id, unixTime, msgtext, userID)

# the tail of the geojson file
output += \
''' \
]

}
'''


# opens an geoJSON file to write the output
outFileHandle = open("filename.geojson", "w")
outFileHandle.write(output)
outFileHandle.close()

Validation

It’s very important to make sure your json file in a nice formatting. And one more important thing, don’t forget to remove , in geojson file aftet the last Feature manully.

Some online validators can easily reach. JSON Formatter

Some special characters will couse invalid of geojson, e.g. @:~{} and etc. So you would like to remove them before visualization.

Reference

[1] How to convert CSV data to geoJSON