У меня есть база данных, полная широты и долготы, которую я хочу нанести на карту листовки. Я создаю приложение Blazor Server. Проблема в том, что InitMap не вызывается, или есть проблема с отправкой параметра в функцию Javascript InitMap.
Я получаю следующие ошибки:
WASM: Система .Text. Json .JsonException: значение JSON не может быть преобразовано в System.String. Путь: $ | LineNumber: 0 | BytePositionInLine: 1. ---> System.InvalidOperationException: Невозможно получить значение типа токена 'StartObject' в виде строки. blazor.webassembly. js: 1: 35618
WASM: at System.Text. Json .Utf8JsonReader.GetString () <0x2314810 + 0x00036> в <0f07585cda034495a8a1c3ac71a.seb0b1. *: 1: 35618 </p>
WASM: в System.Text. Json .Serialization.Converters.JsonConverterString.Read (System.Text. Json .Utf8JsonReader & reader, тип System.TypeToConvert, System.Text. Json .JsonSerializerOptions options) <0x23145c0 + 0x00004> в <0f07585cda034495a8a1c3ac71cf9d1a>: 0 blazor.webassembly. js: 1: 35618
WASM: в System.Tell. TClass, TDeclaredProperty, TRuntimeProperty, TConverter. *: 1: 35618
WASM: at System.Text. Json .JsonPropertyInfo.Read (System.Text. Json .JsonTokenType tokenType, System.Text. Json .ReadStack & state, System. Текст. Json .Utf8JsonReader & reader) <0x2314090 + 0x00078> в <0f07585cda034495a8a1c3ac71cf9d1a>: 0 blazor.webassembly. js: 1: 35618
WASM: в System.Text. Json .JsonSerializer.HeleTal. ... .JsonTokenType tokenType, System.Text Json .JsonSerializerOptions опции, System.Text Json .Utf8JsonReader & читатель, System.Text Json .ReadStack & состояние) <0x2313c88 + 0x0009a> в <0f07585cda034495a8a1c3ac71cf9d1a>: 0 blazor. webassembly. js: 1: 35618
WASM: at System.Text. Json .JsonSerializer.HandleObjectAsValue (System.Text. Json .JsonTokenType tokenType, System.Text. Json .JsonSerial параметры, System.Text. Json .Utf8JsonReader & reader, System.Text. Json .ReadStack & readStack, System.Text. Json .JsonReaderState & initialState, System.Int64 initialBytesConsumed) <0x2846158 + 0x000a * 1069 в 1069 * 1069 0f07585cda034495a8a1c3ac71cf9d1a>: 0 blazor.webassembly. js: 1: 35618
WASM: в System.Text. Json .JsonSerializer.ReadCore (System.Text. Json .JSONS) . Json .Utf8JsonReader & reader, System.Text. Json .ReadStack & readStack) <0x22fbc98 + 0x0011a> в <0f07585cda034495a8a1c3ac71cf9d1a>: 0
Длинный я из базы данных и добавляет его в список функций.
public async Task<string> GetGeoJSON()
{
var features = new List<Feature>();
foreach (var item in _context.ItemsForTrade)
{
var point = new Point(new Position(item.Latitude, item.Longitude));
var featureProperties = new Dictionary<string, object> { };
features.Add(new Feature(point, featureProperties));
}
var fcol = new GeoJSON.Net.Feature.FeatureCollection(features);
var serializedData = JsonConvert.SerializeObject(fcol, Formatting.Indented);
return serializedData;
}
У меня есть API-контроллер, который вызывает эту службу и возвращает строку -
[HttpGet("[action]")]
public async Task<string> GetGeoJSON()
{
return await wantedItemService.GetGeoJSON();
}
В индексе. html У меня есть метод javascript, который принимает строковый параметр и отправляет его в Leaflet для отображения на карте -
function InitMap(locations) {
var map = L.map('map').locate({setView: true, maxZoom: 16});
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1
}).addTo(map);
var mapIcon= L.icon({
iconUrl: '/images/mapIcon.png',
iconSize: [32, 37],
iconAnchor: [16, 37],
popupAnchor: [0, -28]
});
function onEachFeature(feature, layer) {
var popupContent = "<p>I started out as a GeoJSON " +
feature.geometry.type + ", but now I'm a Leaflet vector!</p>";
if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent);
}
L.geoJSON([locations], {
style: function (feature) {
return feature.properties && feature.properties.style;
},
onEachFeature: onEachFeature,
pointToLayer: function (feature, latlng) {
return L.marker(latlng, { icon: mapIcon });
}
}).addTo(map);
}
И, наконец, в своем компоненте Blazor я вызываю метод API для получения Geo JSON строка и вызов метода Javascript InitMap
Map.blazor
@page "/members/Map"
@inject HttpClient Http
@inject IJSRuntime jsRuntime
@inject Blazored.LocalStorage.ILocalStorageService localStorage
<h2 class="title text-uppercase">Map <span class="text-theme-colored"></span></h2>
<div id="map" class="map map-home" style="height: 800px; margin-top: 50px; margin-bottom: 50px;"></div>
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
string positions = await Http.GetJsonAsync<string>("api/WantedItems/GetGeoJSON");
await jsRuntime.InvokeAsync<string>("InitMap", positions);
}
}