NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

#!/usr/bin/python3
# apt install python3-geopy
# apt install python3-matplotlib

import sys
from geopy.distance import geodesic
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLineEdit, QPushButton, QDoubleSpinBox, QListWidget, QListWidgetItem,
QDesktopWidget, QFileDialog, QLabel
)
from PyQt5.QtCore import Qt
import re

class CoordinateHelper(QMainWindow):
def __init__(self):
super().__init__()
self._is_panning = False
self._pan_start = None
self._lims_x = None
self._lims_y = None
self.initUI()

def initUI(self):
self.setWindowTitle("EVSEGN Cord helper")
screen = QDesktopWidget().screenGeometry()
x = (screen.width() - 800) // 2
y = (screen.height() - 800) // 2
self.setGeometry(x, y, 800, 800)
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.create_widgets()

def create_widgets(self):
self.main_layout = QVBoxLayout()
self.central_widget.setLayout(self.main_layout)

# Input coordinates
input_layout = QHBoxLayout()
self.main_layout.addLayout(input_layout)
input_layout.addWidget(QLabel("Введите координаты (широта, долгота):"))
self.entry = QLineEdit()
self.entry.returnPressed.connect(self.add_coordinate)
input_layout.addWidget(self.entry)

# Distance threshold
thr_layout = QHBoxLayout()
self.main_layout.addLayout(thr_layout)
thr_layout.addWidget(QLabel("Порог расстояния (м):"))
self.distance_threshold_spinbox = QDoubleSpinBox()
self.distance_threshold_spinbox.setRange(1, 100)
self.distance_threshold_spinbox.setValue(25)
thr_layout.addWidget(self.distance_threshold_spinbox)

# Buttons
for text, slot in [
("Добавить координаты", self.add_coordinate),
("Импорт из файла", self.import_coordinates_from_file),
("Экспортировать в GPX", self.export_to_gpx)
]:
btn = QPushButton(text)
btn.clicked.connect(slot)
self.main_layout.addWidget(btn)

# --- Кнопка удаления ---
btn_remove = QPushButton("Удалить выбранные координаты")
btn_remove.clicked.connect(self.remove_selected_coordinate)
self.main_layout.addWidget(btn_remove)
# -----------------------

# List of coordinates
self.main_layout.addWidget(QLabel("Добавленные координаты:"))
self.coordinates_list = QListWidget()
self.coordinates_list.setSelectionMode(QListWidget.ExtendedSelection)
self.coordinates_list.itemClicked.connect(self.on_item_clicked)
self.main_layout.addWidget(self.coordinates_list)

# Plot area
self.fig = Figure(figsize=(10, 6))
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvas(self.fig)
for ev, handler in [
('scroll_event', self.on_scroll),
('button_press_event', self.on_press),
('button_release_event', self.on_release),
('motion_notify_event', self.on_motion)
]:
self.canvas.mpl_connect(ev, handler)
self.main_layout.addWidget(self.canvas)

self.coordinates = []
self.distances = {}

def parse_coordinates(self, s):
parts = s.replace(',', ' ').split()
if len(parts) != 2:
raise ValueError("Недопустимый формат координат. Используйте 'широта, долгота'.")
return float(parts[0]), float(parts[1])

def calculate_distances(self):
self.distances.clear()
for i in range(len(self.coordinates)):
for j in range(i+1, len(self.coordinates)):
d = geodesic(self.coordinates[i], self.coordinates[j]).m
self.distances[(i, j)] = d

def draw_map(self):
self.ax.clear()
self.ax.set_xlabel('Долгота')
self.ax.set_ylabel('Широта')
self.ax.set_title('Расстояние между координатами')

threshold = self.distance_threshold_spinbox.value()
red = {i for (i, j), d in self.distances.items() if d < threshold}
red |= {j for (i, j), d in self.distances.items() if d < threshold}

for i, (lat, lon) in enumerate(self.coordinates):
col = 'red' if i in red else 'blue'
self.ax.plot(lon, lat, 'o', color=col)
self.ax.text(lon, lat, str(i+1), ha='center', va='center')

for (i, j), d in self.distances.items():
if d < threshold:
x = [self.coordinates[i][1], self.coordinates[j][1]]
y = [self.coordinates[i][0], self.coordinates[j][0]]
self.ax.plot(x, y, '-', color='red')
midx, midy = sum(x)/2, sum(y)/2
self.ax.text(midx, midy, f"{d:.2f} m", ha='center', va='center')

self.canvas.draw_idle()

def on_scroll(self, event):
base = 1.2
x, y = event.xdata, event.ydata
if x is None or y is None:
return
cx, cy = self.ax.get_xlim(), self.ax.get_ylim()
sf = 1/base if event.button == 'up' else base
nw, nh = (cx[1]-cx[0])*sf, (cy[1]-cy[0])*sf
relx = (cx[1] - x) / (cx[1] - cx[0])
rely = (cy[1] - y) / (cy[1] - cy[0])
self.ax.set_xlim(x - nw*(1-relx), x + nw*relx)
self.ax.set_ylim(y - nh*(1-rely), y + nh*rely)
self.canvas.draw_idle()

def on_press(self, event):
if event.button == 1:
self._is_panning = True
self._pan_start = (event.x, event.y)
self._lims_x = self.ax.get_xlim()
self._lims_y = self.ax.get_ylim()

def on_motion(self, event):
if not self._is_panning:
return
dx, dy = event.x - self._pan_start[0], event.y - self._pan_start[1]
inv = self.ax.transData.inverted()
st = inv.transform(self._pan_start)
cu = inv.transform((event.x, event.y))
ddx, ddy = st[0]-cu[0], st[1]-cu[1]
self.ax.set_xlim(self._lims_x[0]+ddx, self._lims_x[1]+ddx)
self.ax.set_ylim(self._lims_y[0]+ddy, self._lims_y[1]+ddy)
self.canvas.draw_idle()

def on_release(self, event):
if event.button == 1:
self._is_panning = False

def add_coordinate(self):
try:
lat, lon = self.parse_coordinates(self.entry.text())
self.coordinates.append((lat, lon))
self.coordinates_list.addItem(f"{lat}, {lon}")
self.entry.clear()
self.calculate_distances()
self.draw_map()
except ValueError as e:
print(e)

def import_coordinates_from_file(self):
fn, _ = QFileDialog.getOpenFileName(self, "Импорт", "", "*.txt")
if not fn:
return
coords = []
with open(fn, 'r', encoding='utf-8') as f:
for line in f:
m = re.findall(r"(d+(?:.d+)?)", line)
if len(m) == 2:
coords.append((float(m[0]), float(m[1])))
for lat, lon in coords:
self.coordinates.append((lat, lon))
self.coordinates_list.addItem(f"{lat}, {lon}")
self.calculate_distances()
self.draw_map()

def export_to_gpx(self):
fn, _ = QFileDialog.getSaveFileName(self, "Экспорт", "", "*.gpx")
if not fn:
return
if not fn.lower().endswith('.gpx'):
fn += '.gpx'
with open(fn, 'w', encoding='utf-8') as f:
f.write('<?xml version="1.0"?>n<gpx>n')
for i, (lat, lon) in enumerate(self.coordinates):
f.write(f' <wpt lat="{lat}" lon="{lon}"><name>#{i+1}</name></wpt>n')
f.write('</gpx>n')
print(f"Координаты экспортированы в файл {fn}")

def remove_selected_coordinate(self):
selected_items = self.coordinates_list.selectedItems()
if not selected_items:
return

# Удаляем в обратном порядке, чтобы не сбить индексы
for item in reversed(selected_items):
row = self.coordinates_list.row(item)
self.coordinates_list.takeItem(row)
del self.coordinates[row]

self.calculate_distances()
self.draw_map()

def on_item_clicked(self, item):
self.coordinates_list.setCurrentItem(item)

if __name__ == "__main__":
app = QApplication(sys.argv)
window = CoordinateHelper()
window.show()
sys.exit(app.exec_())
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.