Skip to content

Commit

Permalink
Fixes for Markers and FlightTracker Demo (#33)
Browse files Browse the repository at this point in the history
* Fix to clear shape/marker list
Fix to update maker properties.
Comments

* FlightTracker demo

* move config

* minor extensions

* disable cors for client api call

* dispose timer

* Events sample

---------

Co-authored-by: lolochristen <[email protected]>
  • Loading branch information
lolochristen and lolochristen authored Jan 15, 2024
1 parent a0240c5 commit 2361b16
Show file tree
Hide file tree
Showing 14 changed files with 396 additions and 22 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<Project Sdk="Microsoft.NET.Sdk.Razor">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
Expand All @@ -22,6 +22,7 @@
<EmbeddedResource Include="Pages\SwissMapLayersDemo.razor" />
<EmbeddedResource Include="Pages\DrawDemo.razor" />
<EmbeddedResource Include="Pages\GermanGdzDemo.razor" />
<EmbeddedResource Include="Pages\FlightTracker.razor" />
</ItemGroup>

<ItemGroup>
Expand Down
87 changes: 87 additions & 0 deletions src/OpenLayers.Blazor.Demo.Components/Pages/EventsDemo.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
@page "/events"

<div class="card mt-2 mb-2">
<div class="card-header">
<h3 class="card-title">Events</h3>
@if (_map != null)
{
<pre>
Zoom: @_map.Zoom
Center: @_map.Center
Extent: @_map.VisibleExtent
Pointer: @_pointer
</pre>
}
</div>
<div class="card-body small font-monospace" style="height: 400px; overflow-y: auto;">
@foreach (var m in _msg)
{
<span>
@m<br/>
</span>
}
</div>
</div>

<OpenStreetMap @ref="_map" Style="height: 500px" Class="card mb-2"
CenterChanged="OnCenterChanged"
OnRenderComplete="OnRenderComplete"
OnClick="OnClick"
VisibleExtentChanged="VisibleExtentChanged"
OnPointerMove="OnPointerMove"
ZoomChanged="ZoomChanged"></OpenStreetMap>

@code {
private OpenStreetMap? _map;
private Coordinate? _pointer;
private readonly List<string> _msg = [];

protected override void OnInitialized()
{
AddMessage("Page.OnInitialized");
base.OnInitialized();
}

protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
AddMessage($"Page.OnAfterRender firstRender: {firstRender}");
base.OnAfterRender(firstRender);
}

private void OnCenterChanged(Coordinate c)
{
AddMessage($"CenterChanged {c}");
}

private void AddMessage(string msg)
{
_msg.Insert(0, msg);
}

private void OnRenderComplete()
{
AddMessage("RenderComplete");
}

private void OnClick(Coordinate c)
{
AddMessage($"OnClick {c}");
}

private void VisibleExtentChanged(Extent e)
{
AddMessage($"VisibleExtentChanged {e}");
}

private void OnPointerMove(Coordinate c)
{
_pointer = c;
}

private void ZoomChanged(double z)
{
AddMessage($"ZoomChanged {z}");
}

}
155 changes: 155 additions & 0 deletions src/OpenLayers.Blazor.Demo.Components/Pages/FlightTracker.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
@page "/flighttracker"
@using Microsoft.Extensions.Logging
@using System.Timers
@using System.Runtime.InteropServices
@using System.Text.Json.Serialization
@rendermode Components.RenderMode.DefaultRenderMode
@implements IDisposable

<div class="card mt-2 mb-2">
<div class="card-header">
<h3 class="card-title">Flight Tracker</h3>
</div>
<div class="card-body">
@* CORS might make some troubles. Works best in Blazor Server Mode Demo solution (just a demo, never just create server sided timers). *@
<p>Using markers to show flights using API https://api.adsb.lol.</p>
</div>
</div>

<OpenStreetMap @ref="_map" Style="height: 800px" Class="card mb-2" AutoPopup>
<Popup>
<div id="popup" class="ol-box">
@if (context is Marker marker)
{
var flight = _flightData.Flights.FirstOrDefault(p => p.Id == marker.Id);
<h4>Flight @flight.Name</h4>
<p>Location: @marker.Coordinate.X / @marker.Coordinate.Y</p>
<p>Registration: @flight.Registration @flight.Type</p>
<p>Altitude: @flight.AltitudeBaro Speed (ground): @flight.GroundSpeed</p>
}
</div>
</Popup>

</OpenStreetMap>

<CodeView Source="FlightTracker.razor"/>

@code {
private OpenStreetMap? _map;

[Inject]
HttpClient _httpClient { get; set; }

private Timer? _timer;

[Inject]
private ILogger<FlightTracker> _logger { get; set; }

private AdsbResponse? _flightData;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
_map.Center = new Coordinate(2.79437, 51.89508);
_map.Zoom = 9;
await LoadTrackingData(_map.Center);

_timer = new Timer(new TimeSpan(0, 0, 3));
_timer.Elapsed += async (sender, args) => await LoadTrackingData(_map.Center);
_timer.Start();
}
await base.OnAfterRenderAsync(firstRender);
}

private async Task LoadTrackingData(Coordinate center)
{
try
{
if (_map == null || _map.VisibleExtent == null)
return;

var c1 = new Coordinate(_map.VisibleExtent.X1, _map.VisibleExtent.Y1);
var c2 = new Coordinate(_map.VisibleExtent.X2, _map.VisibleExtent.Y2);
var visibleDistance = c1.DistanceTo(c2);
var nmVisibleRadius = visibleDistance / 2 * 0.5399568; // to nm
var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.adsb.lol/v2/point/{center.Y}/{center.X}/{(int)nmVisibleRadius}");

if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("Browser")))
{
// disable CORS
request.SetBrowserRequestMode(BrowserRequestMode.NoCors);
request.Headers.Add("Access-Control-Allow-Origin", "*");
request.Headers.Add("Access-Control-Allow-Headers", "Origin, Content-Type, Accept");
}

var response = await _httpClient.SendAsync(request);

_flightData = await response.Content.ReadFromJsonAsync<AdsbResponse>();

foreach (var ac in _flightData.Flights)
{
var marker = _map.MarkersList.FirstOrDefault(p => p.Id == ac.Id);

if (marker == null)
{
marker = new Marker(new Coordinate(ac.Lon, ac.Lat), "_content/OpenLayers.Blazor.Demo.Components/airplane.png", 512, 512, 256, 256)
{ Scale = 0.05, Popup = true, Title = ac.Name, Rotation = ac.TrueHeading * Math.PI / 180 };
marker.Id = ac.Id;
_map.MarkersList.Add(marker);
}
{
marker.Coordinate = new Coordinate(ac.Lon, ac.Lat);
marker.Rotation = ac.TrueHeading * Math.PI / 180;
await marker.UpdateShape();
}
}
}
catch (Exception exp)
{
_logger.LogError(exp, "Error reading flight tracking data");
}

await InvokeAsync(StateHasChanged);
}

public void Dispose()
{
_timer?.Dispose();
}

public class AdsbResponse
{
[JsonPropertyName("ac")]
public AdsbFlight[] Flights { get; set; }
}

public class AdsbFlight
{
[JsonPropertyName("hex")]
public string Id { get; set; }

[JsonPropertyName("flight")]
public string? Name { get; set; }

public double Lon { get; set; }
public double Lat { get; set; }

[JsonPropertyName("t")]
public string? Type { get; set; }

[JsonPropertyName("r")]
public string? Registration { get; set; }

[JsonPropertyName("true_heading")]
public double? TrueHeading { get; set; }

[JsonPropertyName("alt_baro")]
public object? AltitudeBaro { get; set; }

[JsonPropertyName("gs")]
public double? GroundSpeed { get; set; }
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<option value="@MarkerType.MarkerFlag">Flag</option>
<option value="@MarkerType.MarkerCustomImage">Custom Image</option>
</select>
<button class="btn btn-primary" @onclick="() => _map.MarkersList.Clear()">Clear</button>
</div>
</div>

Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions src/OpenLayers.Blazor.Demo.Server/Components/Layout/NavMenu.razor
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,18 @@
<span class="oi oi-plus" aria-hidden="true"></span> Draw Shapes
</NavLink>
</div>

<div class="nav-item px-3">
<NavLink class="nav-link" href="/flighttracker">
<span class="oi oi-plus" aria-hidden="true"></span> Flight Tracker
</NavLink>
</div>

<div class="nav-item px-3">
<NavLink class="nav-link" href="/events">
<span class="oi oi-plus" aria-hidden="true"></span> Events
</NavLink>
</div>

</nav>
</div>
Expand Down
12 changes: 12 additions & 0 deletions src/OpenLayers.Blazor.Demo/Shared/NavMenu.razor
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,18 @@
<span class="oi oi-plus" aria-hidden="true"></span> Germany GDZ Demo
</NavLink>
</div>

<div class="nav-item px-3">
<NavLink class="nav-link" href="/flighttracker">
<span class="oi oi-plus" aria-hidden="true"></span> Flight Tracker
</NavLink>
</div>

<div class="nav-item px-3">
<NavLink class="nav-link" href="/events">
<span class="oi oi-plus" aria-hidden="true"></span> Events
</NavLink>
</div>

</nav>
</div>
Expand Down
9 changes: 9 additions & 0 deletions src/OpenLayers.Blazor.Demo/staticwebapp.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"navigationFallback": {
"rewrite": "/index.html"
},
"globalHeaders": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS"
}
}
2 changes: 2 additions & 0 deletions src/OpenLayers.Blazor/Internal/Marker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public Marker(Coordinate point) : this()

public float[]? Anchor { get; set; }

public double? Rotation { get; set; }

public override int GetHashCode()
{
return HashCode.Combine(base.GetHashCode(), Size, Anchor);
Expand Down
Loading

0 comments on commit 2361b16

Please sign in to comment.