Blazor에서 현재 지도 위치 좌표를 가져오기 위해서는 JavaScript를 활용해야 합니다.
Geolocation API는 JavaScript에서 위치 정보를 가져올 수 있는 표준 방법입니다.
Blazor와 JavaScript 간의 상호 작용을 위해 Blazor의 IJSRuntime 서비스를 사용하면 됩니다. 다음은 이 과정을 단계별로 설명한 예제입니다.
1. JavaScript 코드 작성
먼저, 위치 정보를 가져오기 위한 JavaScript 코드를 작성해야 합니다. 이 코드를 Blazor 프로젝트의 wwwroot/index.html 또는 wwwroot/index.cshtml 파일에 추가합니다.
html코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>BlazorApp</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="css/site.css" rel="stylesheet" />
<link href="BlazorApp.styles.css" rel="stylesheet" />
</head>
<body>
<div id="app">Loading...</div>
<script src="_framework/blazor.webassembly.js"></script>
<script>
window.getCurrentPosition = (callback) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
callback({
latitude: position.coords.latitude,
longitude: position.coords.longitude
});
}, (error) => {
console.error(error);
callback(null);
});
} else {
console.error("Geolocation is not supported by this browser.");
callback(null);
}
};
</script>
</body>
</html>
2. Blazor C# 코드 작성
Blazor 구성 요소에서 JavaScript 함수를 호출하여 위치 정보를 가져오는 코드를 작성합니다. @inject IJSRuntime JSRuntime을 사용하여 JavaScript 런타임을 주입한 후, JavaScript 함수를 호출합니다.
csharp코드
@page "/geolocation"
@inject IJSRuntime JSRuntime
<h3>Get Current Position</h3>
<button @onclick="GetLocation">Get Location</button>
@if (location != null)
{
<p>Latitude: @location.Latitude</p>
<p>Longitude: @location.Longitude</p>
}
else if (locationError != null)
{
<p>Error: @locationError</p>
}
@code {
private Location? location;
private string? locationError;
private async Task GetLocation()
{
try
{
location = await JSRuntime.InvokeAsync<Location>("getCurrentPosition", DotNetObjectReference.Create(this));
locationError = null;
}
catch (Exception ex)
{
location = null;
locationError = ex.Message;
}
}
public class Location
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
}
3. Program.cs 파일 수정 (선택 사항)
기본 설정은 그대로 유지해도 되지만, 필요에 따라 Program.cs 파일에서 추가적인 설정을 할 수 있습니다.
요약
JavaScript 코드를
index.html또는index.cshtml에 추가하여 위치 정보를 가져오는 함수를 작성합니다.Blazor 구성 요소에서 JavaScript 함수를 호출하여 위치 정보를 가져옵니다.
위치 정보를 Blazor 구성 요소에서 표시합니다.
이 과정을 통해 Blazor 앱에서 현재 지도 위치 좌표를 가져올 수 있습니다.