C
C#2mo ago
Pyro2817

Using JavaScript with Blazor

I'm currently working on a project that interacts with Google Maps API. It is now mandatory to use Javascript Map API, since it's needed some map manipulation. I have been stuck trying to load the map in the web page without success since yesterday. I read a lot of guides a saw some videos but the outcome is always the same, he cannot find the file. Does anyone have any idea what it could be wrong? Using: .Net 8, Blazor WebAssembly
warn: Microsoft.AspNetCore.Components.Server.Circuits.RemoteRenderer[100]
Unhandled exception rendering component: error loading dynamically imported module: http://localhost:5047/_content/RouteMancer/js/maps.js

Microsoft.JSInterop.JSException: error loading dynamically imported module: http://localhost:5047/_content/RouteMancer/js/maps.js

at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)
at RouteMancer.Components.MapComponents.Map.OnAfterRenderAsync(Boolean firstRender) in Google-Maps-API/RouteMancer/Components/MapComponents/Map.razor:line 16
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
fail: Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
Unhandled exception in circuit 'XrWoEMkJXcoALPayi7sJx8D2J1iqxyvxtEFhihpHly4'.
Microsoft.JSInterop.JSException: error loading dynamically imported module: http://localhost:5047/_content/RouteMancer/js/maps.js

at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)
at RouteMancer.Components.MapComponents.Map.OnAfterRenderAsync(Boolean firstRender) in Google-Maps-API/RouteMancer/Components/MapComponents/Map.razor:line 16
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
warn: Microsoft.AspNetCore.Components.Server.Circuits.RemoteRenderer[100]
Unhandled exception rendering component: error loading dynamically imported module: http://localhost:5047/_content/RouteMancer/js/maps.js

Microsoft.JSInterop.JSException: error loading dynamically imported module: http://localhost:5047/_content/RouteMancer/js/maps.js

at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)
at RouteMancer.Components.MapComponents.Map.OnAfterRenderAsync(Boolean firstRender) in Google-Maps-API/RouteMancer/Components/MapComponents/Map.razor:line 16
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
fail: Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
Unhandled exception in circuit 'XrWoEMkJXcoALPayi7sJx8D2J1iqxyvxtEFhihpHly4'.
Microsoft.JSInterop.JSException: error loading dynamically imported module: http://localhost:5047/_content/RouteMancer/js/maps.js

at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)
at RouteMancer.Components.MapComponents.Map.OnAfterRenderAsync(Boolean firstRender) in Google-Maps-API/RouteMancer/Components/MapComponents/Map.razor:line 16
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
3 Replies
Pyro2817
Pyro28172mo ago
wwwroot/js/maps.js
window.JSMaps = window.JSMaps || (function () {
let initialized = false;
const mapObjects = {};

async function loadApiScript(key, version) {
if (initialized) {
return;
}

(g => {
var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary", q = "__ib__", m = document, b = window;
b = b[c] || (b[c] = {});
var d = b.maps || (b.maps = {}), r = new Set, e = new URLSearchParams, u = () => h || (h = new Promise(async (f, n) => { await (a = m.createElement("script"));
e.set("libraries", [...r] + "");
for (k in g) e.set(k.replace(/[A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]);
e.set("callback", c + ".maps." + q);
a.src = `https://maps.${c}apis.com/maps/api/js?` + e;
d[q] = f;
a.onerror = () => h = n(Error(p + " could not load."));
a.nonce = m.querySelector("script[nonce]")?.nonce || "";
m.head.append(a) }));
d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() => d[l](f, ...n))
})({
key: key,
v: version,
});

initialized = true;
}

async function initMap(elementId, mapOptions, markerOptions) {
...
}

return {
loadApiScript,
initMap
};
})();
window.JSMaps = window.JSMaps || (function () {
let initialized = false;
const mapObjects = {};

async function loadApiScript(key, version) {
if (initialized) {
return;
}

(g => {
var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary", q = "__ib__", m = document, b = window;
b = b[c] || (b[c] = {});
var d = b.maps || (b.maps = {}), r = new Set, e = new URLSearchParams, u = () => h || (h = new Promise(async (f, n) => { await (a = m.createElement("script"));
e.set("libraries", [...r] + "");
for (k in g) e.set(k.replace(/[A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]);
e.set("callback", c + ".maps." + q);
a.src = `https://maps.${c}apis.com/maps/api/js?` + e;
d[q] = f;
a.onerror = () => h = n(Error(p + " could not load."));
a.nonce = m.querySelector("script[nonce]")?.nonce || "";
m.head.append(a) }));
d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() => d[l](f, ...n))
})({
key: key,
v: version,
});

initialized = true;
}

async function initMap(elementId, mapOptions, markerOptions) {
...
}

return {
loadApiScript,
initMap
};
})();
App.razor
@using static RouteMancer.Components.Routes

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="/" />
<link rel="stylesheet" href="app.css" />
<link rel="icon" type="image/png" href="favicon.png" />
<HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" />
</head>

<body class="bg-gray-300">
<Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" />
<script src="./_content/RouteMancer/js/maps.js" defer></script> <---------- the file
<script src="_framework/blazor.web.js"></script>
</body>

</html>
@using static RouteMancer.Components.Routes

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="/" />
<link rel="stylesheet" href="app.css" />
<link rel="icon" type="image/png" href="favicon.png" />
<HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" />
</head>

<body class="bg-gray-300">
<Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" />
<script src="./_content/RouteMancer/js/maps.js" defer></script> <---------- the file
<script src="_framework/blazor.web.js"></script>
</body>

</html>
Map.razor
@inherits ComponentBase
@inject IJSRuntime JS
@implements IAsyncDisposable

<div @ref=@mapElement style="width: 900px; height: 818px;"></div>

@code {
private IJSObjectReference? module;
private ElementReference mapElement;
private bool apiLoaded = false;

protected override async Task OnAfterRenderAsync(bool firstRender) {
if (firstRender) {
if (module is null) {
string path = "./js/maps.js";
module = await JS.InvokeAsync<IJSObjectReference>("import", path);
}

if (!apiLoaded) {
await module.InvokeVoidAsync("JSMaps.loadApiScript", Environment.GetEnvironmentVariable("MAPS_JS_MAP_API_KEY"));
apiLoaded = true;
}

var mapOptions = new {...};
var markerOptions = new {...};

await module.InvokeVoidAsync("JSMaps.initMap", mapElement, mapOptions, markerOptions);
}
}

public async ValueTask DisposeAsync() {
if (module is not null) {
await module.DisposeAsync();
}
}
}
@inherits ComponentBase
@inject IJSRuntime JS
@implements IAsyncDisposable

<div @ref=@mapElement style="width: 900px; height: 818px;"></div>

@code {
private IJSObjectReference? module;
private ElementReference mapElement;
private bool apiLoaded = false;

protected override async Task OnAfterRenderAsync(bool firstRender) {
if (firstRender) {
if (module is null) {
string path = "./js/maps.js";
module = await JS.InvokeAsync<IJSObjectReference>("import", path);
}

if (!apiLoaded) {
await module.InvokeVoidAsync("JSMaps.loadApiScript", Environment.GetEnvironmentVariable("MAPS_JS_MAP_API_KEY"));
apiLoaded = true;
}

var mapOptions = new {...};
var markerOptions = new {...};

await module.InvokeVoidAsync("JSMaps.initMap", mapElement, mapOptions, markerOptions);
}
}

public async ValueTask DisposeAsync() {
if (module is not null) {
await module.DisposeAsync();
}
}
}
Thing from Human Resources
Iirc Blazor Was fully NoJS unless you did some weird workarounds Ran into the same issue a huge while back
Pyro2817
Pyro28172mo ago
I would prefer not to deal with JavaScript, but there's no way to use the api without it :waaaaaaaaaahhhhhh:
Want results from more Discord servers?
Add your server