Search code examples
pythoncoordinatesgeojsonfolium

converting geojson coordinates to plot correctly on folium in Python


To start here is an example of the geojson data:

WESTERN NORTH PACIFIC ROMS GeoJSON: {
  "type": "Polygon",
  "coordinates": [
    [
      [
        -77.52046966552734,
        34.43336486816406
      ],
      [
        -77.44927978515625,
        34.47288513183594
      ],
      [
        -77.39515686035156,
        34.50209426879883
      ],

I want to change this from -180 to 180 to a 0 to 360 longitude system. What's the easiest way to do this?
It's probably simple to just add 360 ahead of all the longitude coords but I can't figure it out im pretty new to Python.

Thanks!


Solution

  • I’m not entirely sure about GeoJSON, but there is a default json module for Python. You can get the JSON, and turn it into a Python dictionary like this:

    import json
    
    # read JSON data
    with open('GeoJSON_file.json') as f: # use a with statement to close the file if an error occurs (good practise and good for readability)
        d = json.loads(f.read()) # read from file and parse the JSON in one line
    
    # process JSON data as dictionary
    pass
    
    # put the JSON data back in the file (optional)
    with open('GeoJSON_file.json', 'w') as f: # note that this overwrites old data
        f.write(json.dumps(d)) # turn the dict back into text, and write it to the file
    
    

    This will handle the JSON data. In terms of turning the 180 coordinates into 360 coordinates, you should just be able to use a simple function.

    def convert(l):
        if l < 0:
            return l + 360
        else:
            return l
    

    Or you could use a lambda (for fun):

    convert = lambda l: l + (0 if l > 0 else 360)
    

    You can call convert just like you would with the function. The difference is that a lambda function is far more compact. It is equivalent (but not exactly the same as) the simple function from earlier.

    To use these functions (lambda or traditional, it doesn’t matter) I would personally advise using a for loop:

    for i in d['coordinates']:
        i[0] = convert(i[0])
        i[1] = convert(i[1])
    

    This should work. I can post full code if anyone wants it, but it should be pretty easy to put together everything I’ve written here into one python file.