Search code examples
javascriptopenlayers

To generate a hexmap in mercator projection with H3 and OpenLayers, there is a gap at -+180 degree


I'll put a part of the code here which is important to understand the problem.

    const createHex = (lat: any, lng: any) => {
        const cell = latLngToCell(lng, lat, 1);
        const coords = cellToBoundary(cell).map((c) => [c[1], c[0]]);
        const polygon = new Polygon([coords]);
    
        const feature = new Feature(polygon);
        vectorSource.addFeature(feature);
    };

    const map = new Map({
        target: 'map',
        layers: [
            new TileLayer({
                source: new TileJSON({
                    url: 'https://api.maptiler.com/maps/satellite/256/tiles.json?key=yFxxWLuQf6QipClqNF0n',
                    crossOrigin: 'anonymous'
                })
            })
        ],
        view: new View({
            center: [0, 0],
            zoom: 2,
            projection: 'EPSG:4326'
        })
    });

    map.on('click', (e) => {
        createHex(e.coordinate[0], e.coordinate[1]);
    });

enter image description here


Solution

  • For best results polygons which cross the antimeridian should be split to form a MultiPolygon, but doing that is not trivial as you need to calculate the intersection points (use a utility such as turf.js). You might be able to get adequate results simply by using extented coordinates to make the polygons contiguous

    let coords = cellToBoundary(cell).map((c) => [c[1], c[0]]);
    if (coords.some((c) => c[0] < -90) && coords.some((c) => c[0] > 90)) {
      coords = coords.map((c) => [c[0] + (c[0] < -90 ? 360 : 0), c[1]]
    }