import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter.ttk import Progressbar
import folium
import zipfile
from xml.etree import ElementTree as ET
import tempfile
import os
def extract_kml_from_kmz(kmz_file):
with zipfile.ZipFile(kmz_file, 'r') as kmz:
kml_file = next(f for f in kmz.namelist() if f.endswith('.kml'))
with tempfile.TemporaryDirectory() as tmpdirname:
kmz.extract(kml_file, tmpdirname)
kml_path = os.path.join(tmpdirname, kml_file)
with open(kml_path, 'r', encoding='utf-8') as f:
return f.read()
ns = {'kml': 'http://www.opengis.net/kml/2.2'}
placemarks = root.findall(".//kml:Placemark", ns)
total_elements = len(placemarks)
progress_window = tk.Tk()
progress_window.title("Przetwarzanie danych")
progress_window.geometry("300x100")
progress_label = tk.Label(progress_window, text=f"Przetwarzanie elementu 0 z {total_elements}")
progress_label.pack()
progress_bar = Progressbar(progress_window, length=200, mode='determinate')
progress_bar.pack(pady=10)
folium_map = folium.Map()
processed_coordinates = set()
all_coords = []
for index, placemark in enumerate(placemarks, start=1):
name = placemark.find("kml:name", ns)
name = name.text if name is not None else f"Element {index}"
point = placemark.find(".//kml:Point/kml:coordinates", ns)
line = placemark.find(".//kml:LineString/kml:coordinates", ns)
if point is not None:
coords = point.text.strip().split(',')
if len(coords) >= 2:
lon, lat = float(coords[0]), float(coords[1])
rounded_coords = round_coordinates(lat, lon)
if rounded_coords not in processed_coordinates:
folium.Marker([lat, lon], popup=name).add_to(folium_map)
processed_coordinates.add(rounded_coords)
all_coords.append([lat, lon])
elif line is not None:
coords_list = [tuple(map(float, coord.split(',')[:2])) for coord in line.text.strip().split()]
if coords_list:
unique_coords = []
for lon, lat in coords_list:
rounded_coords = round_coordinates(lat, lon)
if rounded_coords not in processed_coordinates:
unique_coords.append((lat, lon))
processed_coordinates.add(rounded_coords)
all_coords.append([lat, lon])
if unique_coords:
folium.PolyLine(locations=unique_coords, popup=name).add_to(folium_map)
else:
print(f"Nie można przetworzyć elementu: {name}")
progress_bar['value'] = (index / total_elements) * 100
progress_label.config(text=f"Przetwarzanie elementu {index} z {total_elements}")
progress_window.update()
progress_window.destroy()
if all_coords:
folium_map.fit_bounds(all_coords)
output_file = input_file.rsplit('.', 1)[0] + '_mapa.html'
folium_map.save(output_file)
return output_file
def main():
input_file = select_input_file()
if input_file:
output_file = process_file(input_file)
print(f"Mapa zapisana jako: {output_file}")
messagebox.showinfo("Zakończono", f"Mapa została zapisana jako:\n{output_file}")
else:
print("Nie wybrano pliku. Zamykanie programu.")
if name == "main":
main() -popraw kod bo niektóre punkty są na mapie zaznaczane podwójnie
The issue you're experiencing with points being marked twice on the map is likely due to inconsistent handling of latitude and longitude values, especially regarding their order and variable names. In the KML format, coordinates are provided in the order longitude, latitude, altitude. However, Folium and many mapping libraries expect coordinates in the order latitude, longitude.
In your code, there are places where the longitude and latitude are mixed up, which can lead to duplicates or missing points when rounding and comparing coordinates. Let's fix the code by ensuring consistent handling of coordinates throughout:
Correct the coordinate extraction to maintain consistent order.
Ensure variable names accurately reflect whether they hold latitude or longitude values.
Adjust the rounding precision if necessary.
Here's the corrected code:
python
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter.ttk import Progressbar
import folium
import zipfile
from xml.etree import ElementTree as ET
import tempfile
import os
def select_input_file():
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(title="Wybierz plik KMZ", filetypes=[("Pliki KMZ", "*.kmz")])
return file_path
def extract_kml_from_kmz(kmz_file):
with zipfile.ZipFile(kmz_file, 'r') as kmz:
kml_file = next(f for f in kmz.namelist() if f.endswith('.kml'))
with tempfile.TemporaryDirectory() as tmpdirname:
kmz.extract(kml_file, tmpdirname)
kml_path = os.path.join(tmpdirname, kml_file)
with open(kml_path, 'r', encoding='utf-8') as f:
return f.read()
def round_coordinates(lat, lon, decimal_places=5):
return round(lat, decimal_places), round(lon, decimal_places)
def process_file(input_file):
kml_content = extract_kml_from_kmz(input_file)
root = ET.fromstring(kml_content)
ns = {'kml': 'http://www.opengis.net/kml/2.2'}
placemarks = root.findall(".//kml:Placemark", ns)
total_elements = len(placemarks)
progress_window = tk.Tk()
progress_window.title("Przetwarzanie danych")
progress_window.geometry("300x100")
progress_label = tk.Label(progress_window, text=f"Przetwarzanie elementu 0 z {total_elements}")
progress_label.pack()
progress_bar = Progressbar(progress_window, length=200, mode='determinate')
progress_bar.pack(pady=10)
folium_map = folium.Map()
processed_point_coordinates = set()
all_coords = []
for index, placemark in enumerate(placemarks, start=1):
name = placemark.find("kml:name", ns)
name = name.text if name is not None else f"Element {index}"
point = placemark.find(".//kml:Point/kml:coordinates", ns)
line = placemark.find(".//kml:LineString/kml:coordinates", ns)
if point is not None:
coords = point.text.strip().split(',')
lon = float(coords[0])
lat = float(coords[1])
rounded_coords = round_coordinates(lat, lon)
if rounded_coords not in processed_point_coordinates:
folium.Marker([lat, lon], popup=name).add_to(folium_map)
processed_point_coordinates.add(rounded_coords)
all_coords.append([lat, lon])
elif line is not None:
coord_strings = line.text.strip().split()
coords_list = []
for coord_str in coord_strings:
coord_components = coord_str.split(',')
lon = float(coord_components[0])
lat = float(coord_components[1])
coords_list.append((lat, lon)) # Store in (lat, lon) order
unique_coords = []
seen_coords_in_line = set()
for lat, lon in coords_list:
rounded_coords = round_coordinates(lat, lon)
if rounded_coords not in seen_coords_in_line:
unique_coords.append((lat, lon))
seen_coords_in_line.add(rounded_coords)
all_coords.append([lat, lon])
if unique_coords:
folium.PolyLine(locations=unique_coords, popup=name).add_to(folium_map)
else:
print(f"Nie można przetworzyć elementu: {name}")
progress_bar['value'] = (index / total_elements) * 100
progress_label.config(text=f"Przetwarzanie elementu {index} z {total_elements}")
progress_window.update()
progress_window.destroy()
if all_coords:
folium_map.fit_bounds(all_coords)
output_file = input_file.rsplit('.', 1)[0] + '_mapa.html'
folium_map.save(output_file)
return output_file
def main():
input_file = select_input_file()
if input_file:
output_file = process_file(input_file)
print(f"Mapa zapisana jako: {output_file}")
messagebox.showinfo("Zakończono", f"Mapa została zapisana jako:\n{output_file}")
else:
print("Nie wybrano pliku. Zamykanie programu.")
if __name__ == "__main__":
main()
Explanation of Changes:
Coordinate Extraction in LineStrings:
We adjusted how coordinates are extracted from LineStrings to ensure they are stored in (lat, lon) order:
python
coord_strings = line.text.strip().split()
coords_list = []
for coord_str in coord_strings:
coord_components = coord_str.split(',')
lon = float(coord_components[0])
lat = float(coord_components[1])
coords_list.append((lat, lon)) # Store in (lat, lon) order
Variable Naming Consistency:
We ensured variables are named appropriately (lat, lon) to avoid confusion and potential bugs.
Rounding Precision:
We adjusted the rounding precision in round_coordinates to 5 decimal places to effectively group points that are very close to each other, potentially representing the same location due to minor differences in the data:
We used processed_point_coordinates to track unique point markers, ensuring that points are only added once to the map. For LineStrings, we used a separate seen_coords_in_line set to prevent duplicate coordinates within the same LineString but allowed the same coordinate to appear in different LineStrings.
Consistent Coordinate Order When Adding to Folium:
We made sure that whenever coordinates are added to Folium (either as a marker or as part of a PolyLine), they are provided in (lat, lon) order, as expected by Folium.
By making these changes, the code should now correctly handle duplicate points and prevent them from being marked multiple times on the map. This should fix the issue you were experiencing.
Note: Always ensure that coordinate data is handled consistently throughout your code, and be mindful of the expected order of latitude and longitude when interfacing with mapping libraries.