将JSON数据传递给JavaScript而不创建新对象

发布于 2025-01-27 07:52:36 字数 2296 浏览 3 评论 0 原文

我正在查询数据库中的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();
  }
};

I am querying json data from database then performing some filtering and further procedures. After that I want to display that data on map, so I am passing it through JSInterop to JavaScript. Everything seems to be working except that on each method execution I am getting new map on my webpage. So after executing method 4 times, I am having 4 maps on web page.

Please comment, if additional code is necessary...

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

椵侞 2025-02-03 07:52:36

我以前从未使用过此地图引擎,但我建议

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
  })
});

应该

if(! document.map){
     document.map = new ol.Map({
      overlays: [overlay],
      target: 'map',
      layers: layers,
      view: new ol.View({
        center: ol.proj.fromLonLat([25.2849, 60.0917]),
        zoom: 8
      })
    });
}
const map = document.map

这基本上说获得已经创建的映射,并且只能创建一个新地图,如果不存在,

请记住,因为您一遍又一遍地使用相同的地图需要

之前

map.addLayer(vectorLayer);
map.addLayer(nauticLayer

在此

for(const layer of map.getLayers())
{
    map.removeLayer(layer)
}

清理先前的运行IE (请注意,这是演示想法而不是功能代码的示例代码)

您还应避免使用 var 关键字,而应该使用 const and var从引入范围前的JS的早期开始,如果以错误的方式使用它,它会产生一些讨厌的副作用

i've not used this map engine before but i would suggest

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
  })
});

should be

if(! document.map){
     document.map = new ol.Map({
      overlays: [overlay],
      target: 'map',
      layers: layers,
      view: new ol.View({
        center: ol.proj.fromLonLat([25.2849, 60.0917]),
        zoom: 8
      })
    });
}
const map = document.map

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

map.addLayer(vectorLayer);
map.addLayer(nauticLayer

do

for(const layer of map.getLayers())
{
    map.removeLayer(layer)
}

(note this is example code to demonstrate the idea, not functioning code)

you should also avoid the var keyword instead you should use const and let 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文