Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically render GeoJSON to image file

Tags:

python

geojson

I have a series of GeoJSON objects that I wish to render on a map programatically.

I can use http://geojson.io and upload my GeoJSON but how do I programatically do this and export a PNG or other image file?

https://github.com/mapbox/geojson.io looked great, but it posts publicly to the geojson.io site.

like image 443
LearningSlowly Avatar asked Oct 17 '25 18:10

LearningSlowly


1 Answers

You'll need to get hold of the MapBox SDK for Python: pip install mapbox

https://github.com/mapbox/mapbox-sdk-py

Then you can use a service like: Static Maps V4 (alternatively Static Styles V1 also looks interesting)

https://www.mapbox.com/api-documentation/pages/static_classic.html

This is the code from their example: https://github.com/mapbox/mapbox-sdk-py/blob/master/docs/static.md#static-maps

main.py

from mapbox import Static

service = Static()

portland = {
    'type': 'Feature',
    'properties': {'name': 'Portland, OR'},
    'geometry': {
        'type': 'Point',
        'coordinates': [-122.7282, 45.5801]}}
response = service.image('mapbox.satellite', features=[portland])

# add to a file
with open('./output_file.png', 'wb') as output:
    _ = output.write(response.content)

run: export MAPBOX_ACCESS_TOKEN="YOUR_MAP_BOX_TOKEN" && python main.py

The above code is working for me and creates a png of the surrounding area of the provided data, as shown below. The features attribute should accept your geojson objects.

Output of python script: main.py

If you want to use a custom MapBox style then you need to use Static Styles V1

https://www.mapbox.com/api-documentation/?language=Python#static

main.py

from mapbox import StaticStyle

service = StaticStyle()

portland = {
    'type': 'Feature',
    'properties': {'name': 'Portland, OR'},
    'geometry': {
        'type': 'Point',
        'coordinates': [-122.7282, 45.5801]}}
response = service.image('YOUR_USERNAME', 'YOUR_STYLE_ID', features=[portland])


# add to a file
with open('./output_file.png', 'wb') as output:
    _ = output.write(response.content)

Styled map output

I've also created a repository on GitHub with an example function: https://github.com/sarcoma/MapBox-Static-Style-Python-Script

like image 86
OrderAndChaos Avatar answered Oct 20 '25 06:10

OrderAndChaos