1

In my CSV file, the Latitude and Longitude coordinates are stored in the same column 'coordinates'.

CSV example:

title;status;coordinates
Title1;active;48.08871174971783, -1.6800857423296234

Here is my code to render markers:

var datas = L.geoCsv(data, {
          firstLineTitles: true,
          fieldSeparator: ';',
          lineSeparator: '\n',
          latitudeTitle: 'coordinates',
          longitudeTitle: 'coordinates',
          debug: true,
          pointToLayer: function (feature, latlng) {
            return L.marker(latlng, {});
          },
...

I can't specify/extract the value on latitudeTitle and longitudeTitle params.

If I split data inside the 2 columns Lat and Lng, It' works.

But I do not always master the construction of the CSV file.

I can extract values in new vars :

var coordinatesArgs = feature.properties.coordinates.split(',');
return L.marker([coordinatesArgs[0], coordinatesArgs[1]], {});

But in my CSV file, I need to keep 2 columns lat and lng...

2
  • What is data: reference to a file, string or object?
    – TomazicM
    Aug 18 at 18:10
  • data is the variable that stores datas from a csv file. Here is the start code : fetch("assets/datas/csv/myfile.csv").then(response => response.text()).then(data => {...
    – user210554
    Aug 18 at 19:58

1 Answer 1

0

This is not really a GIS related question, but essentially a pure JS related one, but anyway...

CSV text, loaded with fetch, has to be changed/transformed with standard JS functions/methods into desired from. On possible way to do this is to break it into array with .split and .map methods, modify content and then convert it back to string with .map and .join methods.

Procedure goes like this:

  • convert string to array of lines with .split('\n') method;
  • convert each line to array of CSV column values with .split(';') method;
  • iterate through line array and convert last element containing joined coordinates into two elements with .split(',') method;
  • convert array back to string with .map and .join methods.

Relevant part of the code could then look something like this:

fetch("assets/datas/csv/myfile.csv").then(response => response.text()).then(data => {
  var parsedContent = data.split('\n').map(e => e.split(';'));
  var lastInd = parsedContent[0].length - 1;
  parsedContent[0][lastInd] = 'lat';
  parsedContent[0][lastInd + 1] = 'lng';
  for (var i = 1; i < parsedContent.length; i++) {
    var coords = parsedContent[i][lastInd].split(',');
    parsedContent[i][lastInd] = coords[0];
    parsedContent[i][lastInd + 1] = coords[1];
  }
  var modifiedData = parsedContent.map(e => e.join(';')).join('\n');
  var datas = L.geoCsv(modifiedData, {
  ...
  ...
});

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.