0

I need to store consecutive latitudes and longitudes in a JSON file for displaying a path on a Leaflet map. As per the documentation, this file needs to look like this:

{"geometry": {"type": "LineString","coordinates": [
    [lon1,lat1],
    [lon2,lat2],
    [lon3,lat3],
    ...
]},"type":"Feature","properties":{}}

Since new coordinates need to be not appended to the file, but inserted before the end, I'm using the method described in the second answer here:

import fileinput
...
while True:
    ...
    geo = geo + "[" + str(lon) + "," + str(lat) + "]"
    for jsonline in fileinput.FileInput(jsonFile,inplace=1):
        if( ']},"type":"Feature","properties' in jsonline):
            jsonline = jsonline.replace( jsonline, geo + jsonline )
        print(jsonline,)

Before running, the file looks like this:

{"geometry": {"type": "LineString","coordinates": [
]},"type":"Feature","properties":{}}

Trouble is, after first run, the file looks like this:

{"geometry": {"type": "LineString","coordinates": [

[lon1,lat1]]},"type":"Feature","properties":{}}

As you can see, there's a line break too much before the first lat/lon pair. After second run, it looks like this:

{"geometry": {"type": "LineString","coordinates": [



[lon1,lat1],[lon2,lat2]]},"type":"Feature","properties":{}}

Now there's four. And then there's eight. And then sixteen. You can see where this is going.

Why in the world is this happening? And what can I do to avoid it?

OZ1SEJ
  • 377
  • 1
  • 3
  • 13

0 Answers0