How to load GeoJson file properly? - python

I have a geojson file of Moscow districts that is avaliable at
http://gis-lab.info/data/mos-adm/mo.geojson
So, I can't load it properly.
These ideas does not help:
GeoJSON data not displaying in Python folium map
GeoJson usage in folium
I tried to create a map and then add a layer on it.
import folium
m = folium.Map(location = [55.7522200,37.6156000], zoom_start_13)
folium.GeoJson(open('mo.geojson')).add_to(m)'
this does not work

Try folium.GeoJson(open('mo.geojson').read()).add_to(m)
This reads the contents of the file and passes the string to folium.

Related

How to create a Wind Rose in KML format (google earth) using Python

I need to create a Wind Rose KML file to be opened in google earth with as (similar to) the following pictures.
I can create wind roses using windrose python module, like this one:
And I know how to create KML points and lines in python using simplekml module like this one:
Does anyone know any package capable of doing that?
or any idea of how to do it?
If you use matplotlib when draw windrose, try to save the fig with following opthons.
plt.axis('off')
plt.savefig('windrose.png', bbox_inches='tight', pad_inches=0, transparent=True)
After you got the image file, generate ground overlay code in kml.
import simplekml
kml = simplekml.Kml(open=1)
doc = kml.newdocument(name='sample', open=1, visibility=0)
ground = doc.newgroundoverlay(name='windrose example')
ground.icon.href = 'windrose.png'
ground.altitudemode = simplekml.AltitudeMode.absolute
ground.altitude = 500.0
ground.latlonbox.north = 38.031368255615234
ground.latlonbox.south = 37.11344909667969
ground.latlonbox.east = 141.5791015625
ground.latlonbox.west = 140.4208984375
ground.visibility = 1
kml.save('sample.kml')
Each values are need to adjust.
Please refer following, if you'd like to know more about ground overlay.
https://developers.google.com/kml/documentation/altitudemode#absolute
Open Google Earth.
Draw a static picture\chart like wanted one over a map.
Save it into a KML file.
Open with any text editor.
It must show you an example which lead you to generate a valid KML with your data.

Folium custom tile map shows only grey box

I use folium to program a leaflet map which I want to customize with an open map from https://sg.geodatenzentrum.de/wms_webatlasde.light_grau. I don't receive an error, but the tile is not displayed: I only get a grey box. I read folium custom map tiles but I still haven't understood how sometimes custom tiles have to be given in a form like:
http://tile.stamen.com/toner/{z}/{x}/{y}.png
http://tile.stamen.com/terrain/{z}/{x}/{y}.jpg
http://tile.stamen.com/watercolor/{z}/{x}/{y}.jpg
I use the map as in the java script source code of the following map: https://www.zdm-emob.de/Kartendarstellung/konzepte.asp. Therefore, I don't get where I went wrong. I assume it could also have something to do with the projection of leaflet and the other map, I tried adjusting but without success.
Here is the code I am using:
import folium
ger = 'https://sg.geodatenzentrum.de/wms_webatlasde.light_grau'
m = folium.Map(location=['51.133333','10.416667'],
tiles = ger,
attr = 'some_attribute',
zoom_start=6)
m
Instead of importing the map as tile in folium.Map one can create a map with a "None" tile. Then, folium.raster_layers.WmsTileLayer can be added to my_map
my_map = folium.Map(tiles=None,min_zoom=6, max_zoom=12, zoom_start=6)
attribute = ('&copy GeoBasis-DE /BKG')
folium.raster_layers.WmsTileLayer(url = 'https://sgx.geodatenzentrum.de/wms_webatlasde.light_grau?',
layers='webatlasde.light_grau',
fmt='image/png',
attr=attribute,
transparent=False).add_to(my_map)

Is there a limit to plotting markers with folium?

I'm plotting the missions ran by the USAF on North Korea during the Korean War.
The following is the map with 2800 plots.
I have a total of about 7500 plots, but whenever I try to plot above 2800 a blank map renders. I'm rendering on a pc laptop. Would it render if I use a desktop? Or is this a limit with folium?
I'm not speculating that it's an issue with the data. I'll share the coordinates data in case someone would like to explore it: link to public excel sheet.
As #Bob Haffner suggested you can use FastMarkerCluster from Folium library.
Here is my code, in my file there is ~500K points.
import pandas as pd
import json
from folium.plugins import FastMarkerCluster
rome_lat, rome_lng = 41.9028, 12.4964
with open("file_name.json", 'r') as f:
# create a new DataFrame
samples = pd.DataFrame(json.loads(f.read()))
# init the folium map object
my_map = folium.Map(location=[rome_lat, rome_lng], zoom_start=5)
# add all the point from the file to the map object using FastMarkerCluster
my_map.add_child(FastMarkerCluster(samples[['latitude', 'longitude']].values.tolist()))
# save the map
my_map.save("save_file.html")
This code takes ~10ms to render the map.
For more details example please follow this link:
FastMarkerCluster example
Hope this is helpful.
Another option is that we can add a specific number of markers(let's say 3000 markers) on a layer, using folium.map.FeatureGroup() function that will add 3000 markers on a single layer, and we can add that layer to the map using add_child() function, which reduces the number of layers on the map. I got the result for 20,000 Markers and 3000 line string. And is able to load within 40-45 seconds.

Turning HTML generated from gmplot into the actual map

Afternoon,
I am trying to use the gmplot library to plot a load of lats/long coordinates I have. If I just take the example on the pypi page, see below (https://pypi.python.org/pypi/gmplot/1.0.5) and run it, I generate the HTML file but I don't know how to turn this into the actual map. Any ideas?
gmap = gmplot.GoogleMapPlotter(37.428, -122.145, 16)
gmap.plot(latitudes, longitudes, 'cornflowerblue', edge_width=10)
gmap.scatter(more_lats, more_lngs, '#3B0B39', size=40, marker=False)
gmap.scatter(marker_lats, marker_lngs, 'k', marker=True)
gmap.heatmap(heat_lats, heat_lngs)
gmap.draw("mymap.html")
gmap.draw("mymap.html")
This will generate the map in your folder where your notebook is, or your file where you have written the code. If you want the map to be generated at some other location specify the path at gmap.draw(<path for map>).
This map can be opened in any browser. Generated map by gmplot has javascript based zoomin capability and the entire map can be accessed through the browser

Python ipyleaflet export map as PNG or JPG or SVG

I have tried to export a visualisation of data with ipyleaflet as PNG or any other file format but i could not find a method that is working. For example in folium there is map.save(path). Is there a library or method in ipyleaflet that i have missed in my research which helps me to accomplish my goal?
here is some example code to generate a map
from ipyleaflet import *
center = [34.6252978589571, -77.34580993652344]
zoom = 10
m = Map(default_tiles=TileLayer(opacity=1.0), center=center, zoom=zoom)
m
I'd like to export this map as an image file without taking a screenshot manually.
I found two sources that allow to export javascript leaflet maps:
https://github.com/aratcliffe/Leaflet.print and https://github.com/mapbox/leaflet-image
Unfortunately i was not able to make use of them in python.
My colleague and I found a decent work around for ipyleaflet (python) image export. Here is how it works. The folium library is required for an export. The GeoJson data in this example is already prepared with style properties:
import folium
map = folium.Map([51., 12.], zoom_start=6,control_scale=True)
folium.GeoJson(data).add_to(map)
map.save('map.html')
This is how the result looks:
The html file can be further processed in python (windows) with subprocess calls to make a PDF or PNG out of it. I hope this helps as the ipyleaflet doc for python is almost non existant.
For generating html, you can use ipywidgets
from ipywidgets.embed import embed_minimal_html
embed_minimal_html('map.html', views=[m])
If you want to make a PNG, you can use ipywebrtc, more specifically:
https://ipywebrtc.readthedocs.io/en/latest/ImageRecorder.html
https://ipywebrtc.readthedocs.io/en/latest/WidgetStream.html
Or in code:
from ipywebrtc import WidgetStream, ImageRecorder
widget_stream = WidgetStream(widget=m, max_fps=1)
image_recorder = ImageRecorder(stream=widget_stream)
display(image_recorder)
Saving the PNG:
with open('map.png', 'wb') as f:
f.write(image_recorder.image.value)
Or converting to pillow image for preprocessing:
import PIL.Image
import io
im = PIL.Image.open(io.BytesIO(image_recorder.image.value))
ipyleaflet supports saving as html. Export of svg and png does not seem to be supported.
https://ipyleaflet.readthedocs.io/en/latest/map_and_basemaps/map.html#save-to-html
m.save('output.html')
I created an issue ticket for ipyleaflet:
https://github.com/jupyter-widgets/ipyleaflet/issues/1083

Categories