How to get back latitude and longitude from the browser to a view
I tried many things below is my latest attempt. The main issue is that the data is not serialized back ... possibly because is returning a function and not data. (When I hard code the object it returns the object) Any advise?

As you can see the Js method is being invoked

but I dont get the response serialized on: var result = await JSRuntime.Current.InvokeAsync
See full code example:
<h6>CSHTML</h6>
@page "/geo"
<pre>@Latitude</pre>
<br>
<pre>@Longitude</pre>
@functions {
private string Latitude { get; set; }
public string Longitude { get; set; }
private class LocationVm {
public string Latitude { get; set; }
public string Longitude { get; set; }
}
protected override async Task OnInitAsync()
{
var result = await JSRuntime.Current.InvokeAsync<LocationVm>("HuliGeolocation.GetLocation");
}
}
`
`
(window as any).HuliGeolocation =
{
GetLocation: () => {
var Latitude = "";
var Longitude = "";
let myFunction = function () {
navigator.geolocation.getCurrentPosition((position) => {
console.log("test");
console.log(position);
return {
Latitude : position.coords.latitude.toString(),
Longitude: position.coords.longitude.toString()
}
});
};
return myFunction();
},
};
Well the issue is that you're attempting to return from the callback function, but you return nothing from the myFunction function. As the getCurrentPosition API is asynchronous / callback based, you need to return a Promise from GetLocation and resolve that promise from the callback where you're currently returning.
Look at the method "readUploadedFileAsText" here https://github.com/RemiBou/Toss.Blazor/blob/master/Toss/Toss.Client/wwwroot/site.js. You have to create a Promise and call resolve with the result you want to get from C#
Thanks for answering, @Suchiman and @RemiBou!
Final solution that fixed my problem. Thank you for the hint.
(window as any).HuliGeolocation =
{
GetLocation: () => {
var myPromise= new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
position => {
let geoLocation = {
Latitude: position.coords.latitude.toString(),
Longitude: position.coords.longitude.toString()
}
resolve(geoLocation);
},
error => { reject(error) }
)
}).catch(error => error);
return myPromise;
},
};
@functions {
private double Latitude { get; set; }
public double Longitude { get; set; }
public class GeoLocation
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
protected override async Task OnInitAsync()
{
var result = await JSRuntime.Current.InvokeAsync<GeoLocation>("HuliGeolocation.GetLocation");
Latitude = result.Latitude;
Longitude = result.Longitude;
}
}