Динамическое обновление позиции массива функций не работает после чтения данных с сервера - PullRequest
0 голосов
/ 02 июля 2019

У меня есть следующий фрагмент кода ниже, где позиции не отображаются на карте и после 4 дней поиска я до сих пор не знаю почему. Может кто-то помочь мне, пожалуйста? Я действительно не знаю, почему это не работает. Данные корректно извлекаются из веб-сервиса в мой JavaScript, но карта становится пустой: (* ​​1001 *

Любая помощь будет принята с благодарностью. Заранее спасибо.

Это работает, если я обновляю несколько точек без выборки данных с сервера, как в примере ниже

var baseMapLayer = new ol.layer.Tile({
  source: new ol.source.OSM()
});
var map = new ol.Map({
  target: 'map',
  layers: [ baseMapLayer],
  view: new ol.View({
          center: ol.proj.fromLonLat([-9.294444444,38.70833333]), // Cordinates of EDISOFT
          zoom: 7 //Initial Zoom Level
        })
});

var myMarkerFeatures = [];

//Adding a marker on the map near sines

var marker1 = new ol.Feature({
  geometry: new ol.geom.Point(
    ol.proj.fromLonLat([-9.294444444,37.70833333])
  ),  // Cordinates of EDISOFT Thales in Paço de Arcos

});

marker1.setStyle(new ol.style.Style({
        image: new ol.style.Icon(({
            crossOrigin: 'anonymous',
            src: 'AISSymbols/cargo-ship.png',
        scale: 0.30

        })),
    text: new ol.style.Text({
            text: '501',
            fill: new ol.style.Fill({color: 'black'}),
            stroke: new ol.style.Stroke({color: 'yellow', width: 1}),
            offsetX: -20,
            offsetY: 20
        })
    }));

marker1.setId(501);


//Adding a marker on the map near EDIOSFT
var marker2 = new ol.Feature({
  geometry: new ol.geom.Point(
    ol.proj.fromLonLat([-9.294444444,38.70833333])
  ),  // Cordinates of 1 degree to the west of EDISOFT location

});
marker2.setStyle(new ol.style.Style({
        image: new ol.style.Icon(({
            crossOrigin: 
'anonymous',
            src: 'AISSymbols/AIS_Vessel.svg',
        rotation: Math.PI / 4.0,
        scale: 0.30

        })),
    text: new ol.style.Text({
            text: '502',
            fill: new ol.style.Fill({color: 'black'}),
            stroke: new ol.style.Stroke({color: 'red', width: 1}),
            offsetX: -20,
            offsetY: 20
        })

    }));
marker2.setId(502);

//myMarkerFeatures = [marker1, marker2];

var vectorSource = new ol.source.Vector({
  features: myMarkerFeatures
});


myMarkerFeatures.push(marker1);
myMarkerFeatures.push(marker2);


//Adding a marker on the map near shore
var markerVectorLayer = new ol.layer.Vector({
  source: vectorSource,

});
map.addLayer(markerVectorLayer);


var marker = new ol.Feature({
  geometry: new ol.geom.Point(
    ol.proj.fromLonLat([-9.694444444,38.70833333])
  ),  // Cordinates of New York's City Hall
});
marker.setStyle(new ol.style.Style({
        image: new ol.style.Icon(({
            crossOrigin: 
'anonymous',
            src: 'AISSymbols/AIS_Vessel.svg',
        rotation: Math.PI / 1.0,
        scale: 0.30

        })),
    text: new ol.style.Text({
            text: '503',
            fill: new ol.style.Fill({color: 'black'}),
            stroke: new ol.style.Stroke({color: 'back', width: 1}),
            offsetX: -20,
            offsetY: 20
        })

    }));
marker.setId(503);
myMarkerFeatures.push(marker);

map.renderSync();
vectorSource.clear(true);
vectorSource.addFeatures(myMarkerFeatures);

//////////////////////////////////////////////////////////

vectorSource.clear(true);
for (var i=0; i<myMarkerFeatures.length;i++){
    if (myMarkerFeatures[i].getId() === 502){
        myMarkerFeatures[i].set('geometry', new ol.geom.Point(getPointFromLongLat(-10.694444444,38.70833333)));
        //myMarkerFeatures[i].getGeometry().setCoordinates([-10.694444444,38.70833333]);
        //myMarkerFeatures[i].getGeometry().setCoordinates(getPointFromLongLat(-10.694444444, 38.70833333));


    }else if (myMarkerFeatures[i].getId() === 501){
        myMarkerFeatures[i].set('geometry', new ol.geom.Point(getPointFromLongLat(-9.294444444,36.70833333)));
        //myMarkerFeatures[i].getGeometry().setCoordinates([-9.294444444,36.70833333]);
        //myMarkerFeatures[i].getGeometry().setCoordinates(getPointFromLongLat(-9.294444444, 36.70833333));
    } else if (myMarkerFeatures[i].getId() === 503){
        myMarkerFeatures[i].set('geometry', new ol.geom.Point(getPointFromLongLat(-9.694444444,39.70833333)));
        //myMarkerFeatures[i].getGeometry().setCoordinates([-9.694444444,39.70833333]);
        //myMarkerFeatures[i].getGeometry().setCoordinates(getPointFromLongLat(-9.694444444, 39.70833333));
    } else {
        alert('Dummy points found');
    }
};

//map.renderSync();

vectorSource.addFeatures(myMarkerFeatures);

function getPointFromLongLat (long, lat) {
    return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857')
}






var baseMapLayer = new ol.layer.Tile({
    source: new ol.source.OSM()
});
var map = new ol.Map({
    target: 'map',
    layers: [baseMapLayer],
    view: new ol.View({
        center: ol.proj.fromLonLat([-9.294444444, 38.70833333]), // Cordinates of EDISOFT
        zoom: 7 //Initial Zoom Level
    })
});


var aisMarkerFeatures = [];
var vectorSource = new ol.source.Vector({
    features: aisMarkerFeatures //add an array of features
});
var vectorLayer = new ol.layer.Vector({
    source: vectorSource
});


map.addLayer(vectorLayer);




function addMarker(MMSI, lon, lat, COG) {

    var found = false;

    for(var i = 0; i < aisMarkerFeatures.length; i++) {
        if (aisMarkerFeatures[i].getId() === MMSI) {
            aisMarkerFeatures[i].set('geometry', new ol.geom.Point(getPointFromLongLat(lon, lat)));
            aisMarkerFeatures[i].setStyle(new ol.style.Style({
                image: new ol.style.Icon(({
                    crossOrigin:
                        'anonymous',
                    src: 'AISMarkers/cargo-ship.png',
                    rotation: Math.PI * COG / 180.0,
                    scale: 0.30
                })),
                text: new ol.style.Text({
                    text: MMSI,
                    fill: new ol.style.Fill({ color: 'black' }),
                    stroke: new ol.style.Stroke({ color: 'black', width: 1 }),
                    offsetX: -20,
                    offsetY: 20
                })
            }));
            found = true;
            break;
        }
    }
    if (found == false) {
        var markerGeometry = new ol.geom.Point(ol.proj.fromLonLat([lon, lat]));
        var markerFeature = new ol.Feature({
            geometry: markerGeometry
        });

        markerFeature.setId(MMSI);

        markerFeature.setStyle(new ol.style.Style({
            image: new ol.style.Icon(({
                crossOrigin:
                    'anonymous',
                src: 'AISMarkers/cargo-ship.png',
                rotation: Math.PI * COG / 180.0,
                scale: 0.30
            })),
            text: new ol.style.Text({
                text: MMSI,
                fill: new ol.style.Fill({ color: 'black' }),
                stroke: new ol.style.Stroke({ color: 'black', width: 1 }),
                offsetX: -20,
                offsetY: 20
            })
        }));
        aisMarkerFeatures.push(markerFeature);
    }


};

function getPointFromLongLat(long, lat) {
    return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857')
}


window.setInterval(function () {

    //clean the layer from any existing markers
    vectorSource.clear(true);

    $.ajax({
        url: 'http://localhost/aisdataretriever/aisdataretriever.asmx/TransferAISPosition',
        type: 'POST',
        cache: false,
        dataType: 'json',
        success: function (aisdata) {
            $.each(aisdata, function (recordCount, aisship) {


                var createMarker = addMarker(aisship.MMSI, aisship.Longitude, aisship.Latitude, aisship.COG);

            });
            //and here add the newly created features to the layer
            vectorSource.addFeatures(aisMarkerFeatures);

        }, error: function () {
            console.log("Connection Failed");
        }
    });
}, 5000);

Карта неожиданно показывается без точек

...