Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export Plotly scatter as kml - python

Is it possible to export a Plotly scatter figure as a kml file? I've got an example below using matplotlib but is it possible to execute the same output using Plotly?

The Plotly figure is a scatter plot. Can it be converted to a kml output? I'm returning an error when trying to export as a kml.

import plotly.express as px
import geopandas as gpd
import simplekml
import matplotlib.pyplot as ppl
from pylab import rcParams

gdf = gpd.read_file(gpd.datasets.get_path("naturalearth_cities"))

gdf['LON'] = gdf['geometry'].x
gdf['LAT'] = gdf['geometry'].y

fig = px.scatter_mapbox(data_frame = gdf, 
                               lat = 'LAT', 
                               lon = 'LON',
                               zoom = 1,
                               mapbox_style = 'carto-positron', 
                               )

fig.show()

fig.write_image('test.kml')

Output:

ValueError: Invalid format 'kml'.
Supported formats: ['png', 'jpg', 'jpeg', 'webp', 'svg', 'pdf', 'eps', 'json']
like image 815
jonboy Avatar asked May 05 '26 18:05

jonboy


1 Answers

If you want to generate KML from the "naturalearth_cities" dataset as a set of placemarks with a point geometry then you can directly create KML from the GeoDataFrame using the to_file() function. You can skip displaying the data in plotly.

Note KML is disabled in Fiona (which is used by geopandas) by default, so it must be enabled before using it.

Python code to write GeoDataFrame to KML output:

import geopandas as gpd

gdf = gpd.read_file(gpd.datasets.get_path("naturalearth_cities"))

# enable KML driver which is disable by default
gpd.io.file.fiona.drvsupport.supported_drivers['KML'] = "rw"

# With newer versions of Fiona, you might need to use libkml
gpd.io.file.fiona.drvsupport.supported_drivers['LIBKML'] = "rw"

gdf.to_file('test.kml', driver='KML')

Output:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document id="root_doc">
    ...
    <Placemark id="test.200">
        <name>Paris</name>
        <ExtendedData>
          <SchemaData schemaUrl="#test.schema">
            <SimpleData name="LON">2.33138946713035</SimpleData>
            <SimpleData name="LAT">48.8686387898146</SimpleData>
          </SchemaData>
        </ExtendedData>
        <Point>
          <coordinates>
            2.33138946713035,48.8686387898146,0
          </coordinates>
        </Point>
    </Placemark>
...

If you want to add a custom style to the KML output, you can instead iterate over the GeoDataFrame and create the KML with simplekml.

like image 174
CodeMonkey Avatar answered May 07 '26 08:05

CodeMonkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!