0

I have a GeoJSON object of line string coordinates, geobj

I am attempting to display them on my OL map object.

  var layer = new ol.layer.Vector({
    source: new ol.source.Vector({
      features: (new ol.format.GeoJSON()).readFeatures(geobj)
    }),
    style: new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: "black",
        width: 10
      }),
    })
  });

  layer.setZIndex(110);
  map_obj.addLayer(layer);

But nothing appears.

I have double checked the coordinates are correct, by plotting them individually on the map.

EDIT: Ran some tests, it's clear the coordiantes are fine. The issue is to do with how I generate the geojson object, I've done this using a loop - something is not quite right with the final product.

var geojsonObject = {
    'type': 'FeatureCollection',
    'crs': {
      'type': 'name',
      'properties': {
        'name': "EPSG:27700",
      },
    },
    'features': []
  };

  $.getJSON(fn, function( data ) {

    data.features.forEach(calculateTraj);

    function calculateTraj(item){

      const MvtSpeed = item.properties.MvtSpeed;
      const MvtDirec = item.properties.MvtSpeed;

      const startLon = item.properties.LonTrajCellCG[0];
      const startLat = item.properties.LatTrajCellCG[0];

      const kmToLon = 1/(111.32 * Math.cos(startLat * (180/Math.PI)));
      let kmToLat   = 1/110.57;

      const distKMin15m = (MvtSpeed * 60 * 60)/1000;
      const alpha = (MvtDirec * (180/Math.PI));

      const deltaLon = (distKMin15m * Math.cos(alpha) * kmToLon);
      const deltaLat = (distKMin15m * Math.cos(alpha) * kmToLat);

      const endLon = parseFloat((startLon + deltaLon).toFixed(4));
      const endLat = parseFloat((startLat + deltaLat).toFixed(4));

      var t1 = ol.proj.fromLonLat([(startLon), (startLat)], ukngProj)
      var t2 = ol.proj.fromLonLat([(endLon), (endLat)], ukngProj)
      geojsonObject.features.push(
        {
          'type': 'Feature',
          'geometry': {
            "type": "LineString",
            "coordinates": [
              [t1], 
              [t2] ],
          },
        });
    }
  });
  return geojsonObject;
}
10
  • Most likely your features are very close to LonLat [0,0] if the geojson is in LonLat. If it is try (new ol.format.GeoJSON()).readFeatures(geobj, {dataProjection: 'EPSG:4326', featureProjection: map_obj.getView().getProjection()})
    – Mike
    Nov 6, 2020 at 17:04
  • That gives an error: Uncaught TypeError: t.addEventListener is not a function. As I say, I dont think its the coordinates, as I have plotted them manually and they appear.
    – dwright
    Nov 6, 2020 at 17:08
  • @Mike Is there a way I could look at the output from source: new ol.source.Vector({ features: (new ol.format.GeoJSON()).readFeatures(geobj) }) ?
    – dwright
    Nov 6, 2020 at 17:11
  • You can retrieve features with layer.getSource().getFeatures() call.
    – TomazicM
    Nov 6, 2020 at 17:41
  • @TomazicM thanks - I'll see what the output there is, could be a clue.
    – dwright
    Nov 6, 2020 at 17:42

1 Answer 1

0

As @TomazicM suggested, this turned out to be a async/sync JS issue. The geojson object returns after my code attempts to display the coordinates. To get round this, I loaded the geoJSON synchronously. I know this is probably not advised, but I couldn't work out how else to do it!

Here is my adapted code:

// function to load gjson synchronously
function loadFileAjaxSync(fn, mimeType) {
  var xmlhttp=new XMLHttpRequest();
  xmlhttp.open("GET",fn,false);
  if (mimeType != null) {
    if (xmlhttp.overrideMimeType) {
      xmlhttp.overrideMimeType(mimeType);
    }
  }
  xmlhttp.send();
  if (xmlhttp.status==200 && xmlhttp.readyState == 4 )
  {
    return xmlhttp.responseText;
  }
  else {
    // TODO Throw exception
    return null;
  }
}

function calcTraj1HRSat(data){

  var geojsonObject = {};
  geojsonObject['type'] = 'FeatureCollection';
  geojsonObject['features'] = [];

  $.each( data.features, function( index, item ) {

    const MvtSpeed = item.properties.MvtSpeed;
    const MvtDirec = item.properties.MvtSpeed;
    
    const startLon = item.properties.LonTrajCellCG[0];
    const startLat = item.properties.LatTrajCellCG[0];
    
    const kmToLon = 1/(111.32 * Math.cos(startLat * (180/Math.PI)));
    let kmToLat   = 1/110.57;
    
    const distKMin15m = (MvtSpeed * 60 * 60)/1000;
    const alpha = (MvtDirec * (180/Math.PI));
    
    const deltaLon = (distKMin15m * Math.cos(alpha) * kmToLon);
    const deltaLat = (distKMin15m * Math.cos(alpha) * kmToLat);
    
    const endLon = parseFloat((startLon + deltaLon).toFixed(4));
    const endLat = parseFloat((startLat + deltaLat).toFixed(4));
    
    var t1 = ol.proj.fromLonLat([(startLon), (startLat)], ukngProj);
    var t2 = ol.proj.fromLonLat([(endLon), (endLat)], ukngProj);
    
    var newFeature = {
      "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [t1, t2]
      },
    }
    geojsonObject['features'].push(newFeature);
  });
  return geojsonObject;
}

// load geojson 
var gjson = loadFileAjaxSync(fn, "application/json");

// do the calculations
f = calcTraj1HRSat(JSON.parse(gjson));

Now I have access to the coordinates in the expected order.

1
  • Instead of having sync AJAX call, you can also have async call. In this case, instead of returning value with return xmlhttp.responseText, just directly process returned data with calcTraj1HRSat(JSON.parse(xmlhttp.responseText)).
    – TomazicM
    Nov 11, 2020 at 10:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.