After converting a Shapefile to GeoJSON I can start creating the svg file. There are some repositories that can help. But I need something more specific.

Conversion from GeoJSON to SVG must meet these requirements:

  • keep the same aspect of the various geographical regions
  • keep the various data for later use (for example the zone ID)
  • create overlapping layers, each with its own id
  • add a custom style to the various elements
  • create and add custom labels for the various elements
  • enlarge the result

I start from what already exists, so with these repositories:

Convertire un file GeoJSON in SVG

I start with the code. Obviously I need a starting GeoJSON file, to read and then to convert to JSON:

I then use geojson2svg to get an array of paths. To keep track of the various data I need a list of the attributes to preserve. I create the attributes variable specifically for this purpose.

After getting svgStr I can merge the various elements of the array so that I can get a string to use to create the SVG file.

Finally I just have to save the file to disk

Add labels to an svg file

To add a label to the various parts of the map I must first locate the center point of each element. There are various algorithms that allow you to do this but the most useful one is called polylabel (it is used to identify the Pole of inaccessibility of each area).

I calculate the POI of each element:

So I save the various points in GeoJSON format:

Then I convert this GeoJSON to an array of SVG element strings:

So I convert this GeoJSON into an array of SVG element strings: To create the actual SVG file, however, I have to work with this array. I need a function that allows me to convert a point to text, and decide which text to use:

Then a function that transforms the array:

Finally I create a parseSVG_poi function to get the complete svg:

Save the result to disk so you can open it with Inkscape:

Use a GeoJSON file with indicated the points where to insert the labels

Of course, it is not necessary to create a temporary variable each time to be used to calculate the position of the labels. I can save this information in a GeoJSON file:

I can use this file whenever I need to retrieve the position of the labels to insert them into the SVG file

Scale the SVG map

This method works quite well but has a problem: the resulting SVG file is often very small. The labels are disproportionate to the boundaries of the zones. To solve this problem I have to scale the whole file. I modified the elrumordelaluz/scale-that-svg repository. I just need a few lines of code to get the result that interests me.

After creating the SVG file all that remains is to use it in an HTML page. But I’ll talk about this in another post.