Skip to content

Instantly share code, notes, and snippets.

@kxrz
Last active June 26, 2024 08:56
Show Gist options
  • Save kxrz/b0447d84989c443b139091eaf8839eb3 to your computer and use it in GitHub Desktop.
Save kxrz/b0447d84989c443b139091eaf8839eb3 to your computer and use it in GitHub Desktop.
Ce script télécharge un fichier KML ou KMZ à partir d’un lien de partage Google MyMaps, extrait les Points of Interest (POIs), et convertit les données en JSON en enregistrant le fichier avec un nom pertinent.
import xmltodict
import json
import requests
import zipfile
import io
import os
def extract_pois(kml_dict):
pois = []
document = kml_dict.get('kml', {}).get('Document', {})
folders = document.get('Folder', [])
if isinstance(folders, dict): # Ensure folders is a list
folders = [folders]
for folder in folders:
placemarks = folder.get('Placemark', [])
if isinstance(placemarks, dict): # Ensure placemarks is a list
placemarks = [placemarks]
for placemark in placemarks:
poi = {}
poi['name'] = placemark.get('name')
poi['description'] = placemark.get('description')
point = placemark.get('Point')
if point:
coordinates = point.get('coordinates')
if coordinates:
lon, lat, _ = map(float, coordinates.split(','))
poi['location'] = {
'latitude': lat,
'longitude': lon
}
pois.append(poi)
return pois
def extract_name(kml_dict):
document = kml_dict.get('kml', {}).get('Document', {})
name = document.get('name')
if name:
return name
return None
def kml_to_json(kml_content, json_file_path):
kml_dict = xmltodict.parse(kml_content)
map_name = extract_name(kml_dict)
pois = extract_pois(kml_dict)
json_content = json.dumps(pois, indent=4, ensure_ascii=False)
if not map_name:
map_name = os.path.splitext(os.path.basename(json_file_path))[0]
json_file_path = f"{map_name}.json"
with open(json_file_path, 'w', encoding='utf-8') as json_file:
json_file.write(json_content)
return json_file_path # Return the actual file path used
def download_kml_or_kmz(url):
response = requests.get(url)
response.raise_for_status() # Ensure we notice bad responses
content_type = response.headers.get('Content-Type')
if 'xml' in content_type or 'kml' in content_type:
return response.content, 'map'
elif 'kmz' in content_type:
with zipfile.ZipFile(io.BytesIO(response.content)) as kmz:
for file_name in kmz.namelist():
if file_name.endswith('.kml'):
with kmz.open(file_name) as kml_file:
return kml_file.read(), os.path.splitext(file_name)[0]
raise ValueError("KMZ file does not contain a KML file")
else:
raise ValueError("URL does not point to a KML or KMZ file")
# Main script
if __name__ == "__main__":
share_url = input("Veuillez entrer l'URL de partage de votre carte Google MyMaps : ")
try:
unique_id = share_url.split("mid=")[-1]
kml_url = f"https://www.google.com/maps/d/kml?mid={unique_id}"
kml_content, default_name = download_kml_or_kmz(kml_url)
json_file_path = kml_to_json(kml_content, f"{default_name}.json")
print(f"Le fichier KML/KMZ a été téléchargé et converti en JSON avec succès sous le nom {json_file_path}.")
except Exception as e:
print(f"Une erreur s'est produite : {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment