将JSON数据传递给JavaScript而不创建新对象
我正在查询数据库中的JSON数据,然后执行一些过滤和进一步的过程。之后,我想在地图上显示该数据,因此我将其通过JSinterop传递给JavaScript。一切似乎都在起作用,除了在每个方法执行中,我都在网页上获得了新的地图。因此,在执行方法4次之后,我在网页上有4个地图。
请评论,如果需要其他代码...
index.Razor:
<div>
<select id="layer-select" style="visibility:hidden;">
<option value="osm" selected>Open Street Map</option>
</select>
<div class="card-body p-0">
<div id="map"></div>
<div id="popup" class="ol-popup">
<a href="#" id="popup-closer" class="ol-popup-closer"></a>
<div id="popup-content"></div>
</div>
</div>
</div>
index.razor.cs:
[Inject] IJSRuntime JSRuntime { get; set; }
...
private async Task UpdateData()
{
this.SelectedDate = this.SelectedDate.Value.AddDays(1);
this.FilteredDataRecords = this.DataRecords
.Where(w => w.TimeNow.Date == SelectedDate.Value.Date && (w.Latitude != 0 || w.Longitude != 0))
.OrderBy(o => o.TimeNow)
.ToList();
string jsonData = JsonSerializer.Serialize(this.FilteredDataRecords);
await JSRuntime.InvokeAsync<object>("olMap.showMap", jsonData);
}
map.js:
window.olMap = {
showMap: function (jsonData) {
var HereLayers = [
{
base: 'base',
type: 'maptile',
scheme: 'osm',
},
];
...
var vectorLayer = new ol.layer.Vector({
source: loadMarineData(JSON.parse(jsonData)), //JSON.parse(jsonData)
visible: true,
style: new ol.style.Style({
stroke: new ol.style.Stroke({ color: '#d12710', width: 4 })
})
});
var map = new ol.Map({
overlays: [overlay],
target: 'map',
layers: layers,
view: new ol.View({
center: ol.proj.fromLonLat([25.2849, 60.0917]),
zoom: 8
})
});
map.addLayer(vectorLayer);
map.addLayer(nauticLayer);
....
var select = document.getElementById('layer-select');
function onChange() {
var scheme = select.value;
for (var i = 0, ii = layers.length; i < ii; ++i) {
layers[i].setVisible(HereLayers[i].scheme === scheme);
}
}
select.addEventListener('change', onChange);
onChange();
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我以前从未使用过此地图引擎,但我建议
应该
这基本上说获得已经创建的映射,并且只能创建一个新地图,如果不存在,
请记住,因为您一遍又一遍地使用相同的地图需要
之前
在此
清理先前的运行IE (请注意,这是演示想法而不是功能代码的示例代码)
您还应避免使用
var
关键字,而应该使用const and
让
var从引入范围前的JS的早期开始,如果以错误的方式使用它,它会产生一些讨厌的副作用i've not used this map engine before but i would suggest
should be
this basically says get the already created map and only create a new map it if doesn't exist
just remember that because you are using the same map over and over again you will need to clean up the previous runs yourself
ie before
do
(note this is example code to demonstrate the idea, not functioning code)
you should also avoid the
var
keyword instead you should useconst
andlet
var is a hold over from the early days of JS before the introduction of scoping and it has some nasty side effects if you use it in the wrong way