GeoJSON optimizer

author(s): Torstein Hønsi

HTML

<textarea id="input" placeholder="Paste GeoJSON here"></textarea>
<textarea id="output"></textarea>
<button id="run" class="highcharts-demo-button">Optimize</button>
<p class="highcharts-description">Click "Optimize" to strip whitespace from your GeoJSON, and reduce the number of decimals in coordinates.</p>

CSS

body {
    font-family:
        -apple-system,
        BlinkMacSystemFont,
        "Segoe UI",
        Roboto,
        Helvetica,
        Arial,
        "Apple Color Emoji",
        "Segoe UI Emoji",
        "Segoe UI Symbol",
        sans-serif;
}

textarea {
    font-family: monospace;
    margin: 10px;
    width: calc(100% - 22px);
    height: 100px;
}

.highcharts-description {
    margin: 10px;
}

.highcharts-demo-button {
    background: var(--highcharts-neutral-color-5, #f2f2f2);
    border: none;
    border-radius: 4px;
    color: var(--highcharts-neutral-color-100, #000);
    cursor: pointer;
    display: inline-block;
    font-size: 0.8rem;
    padding: 0.5rem 1.5rem;
    margin: 0.5rem -5px 0.5rem 10px;
    transition: background 250ms;
}

.highcharts-demo-button:hover {
    background: var(--highcharts-neutral-color-10, #e6e6e6);
}

JavaScript

const keepDecimals = 0;

document.getElementById('run').click(function () {
    document.getElementById('output').innerText = document.getElementById(
        'input'.value.replace(/\s/g, '')
            .replace(
                /(\[-?\d+)\.(\d+)(,-?\d+)\.(\d+)(\])/g,
                function (s1, s2, s3, s4, s5, s6) {
                    return keepDecimals ? (
                        s2 + '.' + s3.slice(0, keepDecimals) + s4 + '.' +
                        s5.slice(0, keepDecimals) + s6
                    ) : s2 + s4 + s6;
                }
            )
    );
});