unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, System.Math, System.Net.HttpClient, System.Net.URLClient, System.NetEncoding, System.JSON, System.IOUtils, Vcl.Imaging.PngImage, System.Net.HttpClientComponent, System.Generics.Collections, System.StrUtils; type TForm1 = class(TForm) ImageMap: TImage; Panel1: TPanel; EditAddress: TEdit; EditZoom: TEdit; LabelZoom: TLabel; ButtonShowPoint: TButton; LabelStatus: TLabel; CheckBoxFrames: TCheckBox; MemoLog: TMemo; NetHTTPClient1: TNetHTTPClient; NetHTTPRequest1: TNetHTTPRequest; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure ButtonShowPointClick(Sender: TObject); procedure CheckBoxFramesClick(Sender: TObject); private // Przechowuje indeksy centralnego kafelka dla matrycy i rysowania punktu FCenterXTile, FCenterYTile: Integer; // Przechowuje lat, lon dla centrum i markera FCenterLat, FCenterLon: Double; FMarkerLat, FMarkerLon: Double; // Poziom zoomu (domyślnie z=10, ustawiany przez EditZoom) FZoom: Integer; // Ścieżka do folderu cache kafelków FTileCachePath: string; // Ścieżka do pliku logu FLogFilePath: string; // Cache kafelków w pamięci FTileCache: TDictionary; // Bitmapa mapy (kafelki + punkt) FMapBitmap: TBitmap; // Tablica ramek dla kafelków 3x3 FTileFrames: array[-1..1, -1..1] of TRect; // Pobiera współrzędne (lat, lon) z adresu za pomocą Nominatim procedure GeocodeAddress(const Address: string; var Lat, Lon: Double); // Oblicza indeksy centralnego kafelka z lat, lon procedure ComputeCentralTile(Zoom: Integer; Lat, Lon: Double; var XTile, YTile: Integer); // Ładuje matrycę 3x3 kafelków do bitmapy, używając cache procedure Load3x3Matrix(XTile, YTile: Integer; Zoom: Integer; Bitmap: TBitmap); // Rysuje punkt na bitmapie, używając lat, lon procedure DrawPointOnBitmapUsingLatLon(Bitmap: TBitmap; MarkerLat, MarkerLon: Double; Zoom: Integer); // Aktualizuje wyświetlanie mapy (z ramkami lub bez) procedure UpdateMapDisplay; // Inicjalizuje tablicę ramek procedure InitializeTileFrames(Bitmap: TBitmap); // Zwraca ścieżkę do pliku kafelka w cache function GetTileFilePath(Zoom, XTile, YTile: Integer): string; // Pobiera kafelek z cache lub OSM function GetTileFromCacheOrDownload(Zoom, XTile, YTile: Integer): TBitmap; // Loguje komunikat do TMemo i pliku log.txt procedure Log(const Msg: string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var Form1: TForm1; implementation {$R *.dfm} const a = 6378137.0; // Promień Ziemi w metrach dla Web Mercator MAP_EXTENT = 2 * a * Pi; // Zasięg mapy ≈ 40075016.68 m constructor TForm1.Create(AOwner: TComponent); begin inherited; FTileCache := TDictionary.Create; FMapBitmap := TBitmap.Create; FTileCachePath := 'C:\Temp\tile'; FLogFilePath := TPath.Combine(FTileCachePath, 'log.txt'); end; destructor TForm1.Destroy; var Pair: TPair; begin for Pair in FTileCache do Pair.Value.Free; FTileCache.Free; FMapBitmap.Free; inherited; end; procedure TForm1.FormCreate(Sender: TObject); begin // Włącz podpowiedzi dla ImageMap ImageMap.ShowHint := True; // Ustaw domyślny zoom FZoom := 10; EditZoom.Text := '10'; // Utwórz folder cache, jeśli nie istnieje if not TDirectory.Exists(FTileCachePath) then begin try TDirectory.CreateDirectory(FTileCachePath); Log('Utworzono folder cache: ' + FTileCachePath); except on E: Exception do Log('Błąd tworzenia folderu cache: ' + E.Message); end; end; // Wyczyść TMemo MemoLog.Clear; Log('Aplikacja uruchomiona'); // Wywołaj FormResize, aby zainicjować rozmieszczenie komponentów FormResize(Self); end; procedure TForm1.FormResize(Sender: TObject); var TotalWidth, ComponentWidth, Spacing: Integer; begin // Oblicz szerokość i odstępy dla komponentów w Panel1 TotalWidth := Panel1.ClientWidth - 25; // 5 px marginesy z lewej/prawej + 3 odstępy po 5 px ComponentWidth := TotalWidth div 4; // 4 komponenty Spacing := 5; // Ustaw pozycje i szerokości komponentów EditAddress.Left := Spacing; EditAddress.Width := ComponentWidth; EditAddress.Top := 30; EditAddress.Height := 40; EditZoom.Left := EditAddress.Left + EditAddress.Width + Spacing; EditZoom.Width := 60; EditZoom.Top := 30; EditZoom.Height := 40; LabelZoom.Left := EditZoom.Left; LabelZoom.Width := ComponentWidth; LabelZoom.Top := 10; LabelZoom.Height := 40; ButtonShowPoint.Left := 15+EditZoom.Left + EditZoom.Width + Spacing; ButtonShowPoint.Width := 100; ButtonShowPoint.Top := 20; ButtonShowPoint.Height := 40; LabelStatus.Left := 10; LabelStatus.Width := ComponentWidth; LabelStatus.Top := 60; LabelStatus.Height := 40; Label1.Left := Spacing; Label1.Width := ComponentWidth; Label1.Top := 10; Label1.Height := 20; CheckBoxFrames.Left :=15+ ButtonShowPoint.Left + ButtonShowPoint.Width + Spacing; CheckBoxFrames.Width := ComponentWidth; CheckBoxFrames.Top := 20; CheckBoxFrames.Height := 40; end; procedure TForm1.Log(const Msg: string); var LogLine: string; LogFile: TextFile; begin // Dodaj komunikat do TMemo z datą i godziną LogLine := FormatDateTime('yyyy-mm-dd hh:nn:ss', Now) + ': ' + Msg; MemoLog.Lines.Add(LogLine); // Zapisz komunikat do pliku log.txt try AssignFile(LogFile, FLogFilePath); if FileExists(FLogFilePath) then Append(LogFile) else Rewrite(LogFile); Writeln(LogFile, LogLine); CloseFile(LogFile); except on E: Exception do MemoLog.Lines.Add('Błąd zapisu do log.txt: ' + E.Message); end; end; function TForm1.GetTileFilePath(Zoom, XTile, YTile: Integer): string; begin // Generuj ścieżkę do pliku kafelka w formacie C:\Temp\tile\z_x_y.png Result := TPath.Combine(FTileCachePath, Format('%d_%d_%d.png', [Zoom, XTile, YTile])); end; function TForm1.GetTileFromCacheOrDownload(Zoom, XTile, YTile: Integer): TBitmap; var CacheKey, TileFilePath, TileURL: string; Response: IHTTPResponse; Stream: TMemoryStream; PngImage: TPngImage; begin Result := nil; CacheKey := Format('%d_%d_%d', [Zoom, XTile, YTile]); TileFilePath := GetTileFilePath(Zoom, XTile, YTile); TileURL := Format('https://tile.openstreetmap.org/%d/%d/%d.png', [Zoom, XTile, YTile]); // Sprawdź cache w pamięci if FTileCache.TryGetValue(CacheKey, Result) then begin Log('Wczytano kafelek z cache pamięci: ' + CacheKey); Exit; end; // Sprawdź cache na dysku if TFile.Exists(TileFilePath) then begin Result := TBitmap.Create; PngImage := TPngImage.Create; try try PngImage.LoadFromFile(TileFilePath); Result.Assign(PngImage); FTileCache.Add(CacheKey, Result); Log('Wczytano kafelek z cache dysku: ' + TileFilePath); except on E: Exception do begin Result.Free; Result := nil; Log('Błąd wczytywania kafelka z cache: ' + TileFilePath + ', ' + E.Message); if TFile.Exists(TileFilePath) then TFile.Delete(TileFilePath); end; end; finally PngImage.Free; end; end; // Pobierz kafelek z OSM, jeśli nie ma w cache if Result = nil then begin Stream := TMemoryStream.Create; try Sleep(1000); // Ograniczenie czasowe dla OSM Response := NetHTTPClient1.Get(TileURL, Stream); if Response.StatusCode = 200 then begin Stream.Position := 0; Result := TBitmap.Create; PngImage := TPngImage.Create; try PngImage.LoadFromStream(Stream); Result.Assign(PngImage); FTileCache.Add(CacheKey, Result); try PngImage.SaveToFile(TileFilePath); Log('Pobrano i zapisano kafelek: ' + TileFilePath); except on E: Exception do Log('Błąd zapisu kafelka: ' + TileFilePath + ', ' + E.Message); end; finally PngImage.Free; end; end else begin Log('Błąd HTTP dla kafelka: ' + TileURL + ', Status: ' + IntToStr(Response.StatusCode)); end; finally Stream.Free; end; end; end; procedure TForm1.GeocodeAddress(const Address: string; var Lat, Lon: Double); var Response: IHTTPResponse; JSONValue: TJSONValue; JSONArray: TJSONArray; JSONObj: TJSONObject; LatStr, LonStr: string; FormatSettings: TFormatSettings; begin Lat := 0; Lon := 0; FormatSettings := TFormatSettings.Create; FormatSettings.DecimalSeparator := '.'; Log('Rozpoczęto geokodowanie adresu: ' + Address); try Sleep(1000); // Ograniczenie czasowe dla Nominatim Response := NetHTTPClient1.Get('https://nominatim.openstreetmap.org/search?q=' + TNetEncoding.URL.Encode(Address) + '&format=json&limit=1'); Log('Otrzymano odpowiedź HTTP: Status=' + IntToStr(Response.StatusCode)); if Response.StatusCode = 200 then begin JSONValue := TJSONObject.ParseJSONValue(Response.ContentAsString); try Log('Odpowiedź JSON: ' + Response.ContentAsString); if Assigned(JSONValue) and (JSONValue is TJSONArray) and (TJSONArray(JSONValue).Count > 0) then begin JSONArray := TJSONArray(JSONValue); JSONObj := JSONArray.Items[0] as TJSONObject; if JSONObj.TryGetValue('lat', LatStr) and JSONObj.TryGetValue('lon', LonStr) then begin Log('Pobrano lat=' + LatStr + ', lon=' + LonStr); Lat := StrToFloatDef(LatStr, 0, FormatSettings); Lon := StrToFloatDef(LonStr, 0, FormatSettings); if (Lat <> 0) and (Lon <> 0) then begin LabelStatus.Caption := 'Geokodowanie udane';//: lat=' + FloatToStr(Lat) + ', lon=' + FloatToStr(Lon); Log('Geokodowanie udane: lat=' + FloatToStr(Lat) + ', lon=' + FloatToStr(Lon)); end else begin LabelStatus.Caption := 'Niepoprawny format lat/lon w odpowiedzi JSON'; Log('Niepoprawny format lat/lon: lat=' + LatStr + ', lon=' + LonStr); end; end else begin LabelStatus.Caption := 'Brak kluczy lat/lon w odpowiedzi JSON'; Log('Brak kluczy lat/lon w odpowiedzi JSON'); end; end else begin LabelStatus.Caption := 'Brak wyników dla adresu'; Log('Brak wyników dla adresu'); end; finally JSONValue.Free; end; end else begin LabelStatus.Caption := 'Błąd HTTP: ' + IntToStr(Response.StatusCode); Log('Błąd HTTP: ' + IntToStr(Response.StatusCode)); end; except on E: Exception do begin LabelStatus.Caption := 'Błąd geokodowania: ' + E.Message; Log('Błąd geokodowania: ' + E.Message); end; end; end; procedure TForm1.ComputeCentralTile(Zoom: Integer; Lat, Lon: Double; var XTile, YTile: Integer); var XMercator, YMercator: Double; LatRad, LonRad: Double; begin // Oblicz X, Y w metrach dla logowania LatRad := DegToRad(Lat); LonRad := DegToRad(Lon); XMercator := a * LonRad; YMercator := a * Ln(Tan(Pi/4 + LatRad/2)); Log('Obliczono X, Y w metrach: X=' + FloatToStr(XMercator) + ', Y=' + FloatToStr(YMercator)); // Oblicz indeksy kafelka centralnego na podstawie lat, lon XTile := Floor((Lon + 180) / 360 * Power(2, Zoom)); YTile := Floor((1 - Ln(Tan(DegToRad(Lat)) + 1 / Cos(DegToRad(Lat))) / Pi) / 2 * Power(2, Zoom)); Log('Obliczono centralny kafelek: XTile=' + IntToStr(XTile) + ', YTile=' + IntToStr(YTile)); end; procedure TForm1.InitializeTileFrames(Bitmap: TBitmap); var i, j: Integer; TileSize: Integer; begin TileSize := Bitmap.Width div 3; // 768/3 = 256 px for i := -1 to 1 do for j := -1 to 1 do begin FTileFrames[i, j] := Rect((i + 1) * TileSize, (j + 1) * TileSize, (i + 2) * TileSize, (j + 2) * TileSize); end; end; procedure TForm1.Load3x3Matrix(XTile, YTile: Integer; Zoom: Integer; Bitmap: TBitmap); var i, j: Integer; TileSize: Integer; TileBitmap: TBitmap; begin TileSize := Bitmap.Width div 3; // 768/3 = 256 px Log('Ładowanie matrycy 3x3, TileSize=' + IntToStr(TileSize)); NetHTTPClient1.UserAgent := 'OSM Delphi (mciosek@imetroll.com)'; // Inicjalizuj ramki InitializeTileFrames(Bitmap); // Ładuj kafelki for i := -1 to 1 do for j := -1 to 1 do begin TileBitmap := GetTileFromCacheOrDownload(Zoom, XTile + i, YTile + j); if Assigned(TileBitmap) then begin try Bitmap.Canvas.Draw((i + 1) * TileSize, (j + 1) * TileSize, TileBitmap); finally // Nie zwalniaj TileBitmap, bo jest w cache pamięci end; end else begin Log('Nie udało się wczytać kafelka dla pozycji: ' + Format('%d/%d/%d', [Zoom, XTile + i, YTile + j])); end; end; end; procedure TForm1.DrawPointOnBitmapUsingLatLon(Bitmap: TBitmap; MarkerLat, MarkerLon: Double; Zoom: Integer); var n: Double; MarkerPixelX, MarkerPixelY: Double; LeftTopGlobalX, LeftTopGlobalY: Double; MarkerX, MarkerY: Double; TileSize: Integer; GridSize: Integer; begin TileSize := Bitmap.Width div 3; // 768/3 = 256 px GridSize := 3; n := Power(2, Zoom); MarkerPixelX := (MarkerLon + 180) / 360 * n * TileSize; MarkerPixelY := (1 - Ln(Tan(DegToRad(MarkerLat)) + 1 / Cos(DegToRad(MarkerLat))) / Pi) / 2 * n * TileSize; LeftTopGlobalX := (FCenterXTile - (GridSize div 2)) * TileSize; LeftTopGlobalY := (FCenterYTile - (GridSize div 2)) * TileSize; MarkerX := MarkerPixelX - LeftTopGlobalX; MarkerY := MarkerPixelY - LeftTopGlobalY; if (MarkerX >= 0) and (MarkerX < Bitmap.Width) and (MarkerY >= 0) and (MarkerY < Bitmap.Height) then begin Bitmap.Canvas.Pen.Color := clRed; Bitmap.Canvas.Brush.Color := clRed; Bitmap.Canvas.Ellipse(Round(MarkerX - 5), Round(MarkerY - 5), Round(MarkerX + 5), Round(MarkerY + 5)); Log('Narysowano punkt w pozycji: MarkerX=' + FloatToStr(MarkerX) + ', MarkerY=' + FloatToStr(MarkerY)); end else Log('Punkt poza bitmapą: MarkerX=' + FloatToStr(MarkerX) + ', MarkerY=' + FloatToStr(MarkerY)); end; procedure TForm1.UpdateMapDisplay; var i, j: Integer; begin if not Assigned(FMapBitmap) then Exit; // Utwórz nową bitmapę dla ImageMap, aby uniknąć nadpisywania ImageMap.Picture.Bitmap.Width := FMapBitmap.Width; ImageMap.Picture.Bitmap.Height := FMapBitmap.Height; // Kopiuj oryginalną bitmapę mapy ImageMap.Picture.Bitmap.Assign(FMapBitmap); // Rysuj ramki, jeśli włączone if CheckBoxFrames.Checked then begin ImageMap.Picture.Bitmap.Canvas.Pen.Width := 1; // Ramki 1 piksel ImageMap.Picture.Bitmap.Canvas.Brush.Style := bsClear; // Przezroczyste wypełnienie for i := -1 to 1 do for j := -1 to 1 do begin if (i = 0) and (j = 0) then ImageMap.Picture.Bitmap.Canvas.Pen.Color := clRed // Czerwona ramka dla centralnego kafelka else ImageMap.Picture.Bitmap.Canvas.Pen.Color := clGray; // Szare ramki dla pozostałych ImageMap.Picture.Bitmap.Canvas.Rectangle(FTileFrames[i, j]); end; Log('Ramki kafelków włączone'); end else begin Log('Ramki kafelków wyłączone'); end; // Odśwież kontrolkę ImageMap ImageMap.Refresh; end; procedure TForm1.CheckBoxFramesClick(Sender: TObject); begin UpdateMapDisplay; end; procedure TForm1.ButtonShowPointClick(Sender: TObject); var Lat, Lon: Double; XTile, YTile: Integer; begin MemoLog.Clear; Log('Rozpoczęto proces wyświetlania punktu na mapie'); try FZoom := StrToInt(EditZoom.Text); if (FZoom < 1) or (FZoom > 19) then raise Exception.Create('Zoom musi być między 1 a 19'); Log('Zoom ustawiony: ' + IntToStr(FZoom)); except on E: Exception do begin LabelStatus.Caption := 'Błąd zoomu: ' + E.Message; Log('Błąd zoomu: ' + E.Message); Exit; end; end; GeocodeAddress(EditAddress.Text, Lat, Lon); if (Lat = 0) and (Lon = 0) then begin Log('Geokodowanie nie powiodło się, proces przerwany'); Exit; end; FMarkerLat := Lat; FMarkerLon := Lon; FCenterLat := Lat; FCenterLon := Lon; ComputeCentralTile(FZoom, Lat, Lon, XTile, YTile); FCenterXTile := XTile; FCenterYTile := YTile; FMapBitmap.Width := 768; FMapBitmap.Height := 768; FMapBitmap.Canvas.Brush.Color := clWhite; FMapBitmap.Canvas.FillRect(Rect(0, 0, FMapBitmap.Width, FMapBitmap.Height)); Log('Utworzono bitmapę 768x768 px'); Load3x3Matrix(XTile, YTile, FZoom, FMapBitmap); DrawPointOnBitmapUsingLatLon(FMapBitmap, FMarkerLat, FMarkerLon, FZoom); UpdateMapDisplay; Log('Bitmapa przypisana do ImageMap'); end; end.