Skip to content

Instantly share code, notes, and snippets.

@carterpeel
Created June 16, 2024 14:55
Show Gist options
  • Save carterpeel/cb8d9a7ee16d186e544663ee20c5e32b to your computer and use it in GitHub Desktop.
Save carterpeel/cb8d9a7ee16d186e544663ee20c5e32b to your computer and use it in GitHub Desktop.
package geojsonreader
import (
"encoding/json"
"fmt"
"github.com/murphy214/mercantile"
"github.com/paulmach/orb"
gj2 "github.com/paulmach/orb/geojson"
)
type Tile struct {
Tile mercantile.TileID
Lat float64
Lon float64
Index int
}
// TilesFromGeoJSON converts GeoJSON Polygon(s) to MBTiles
func TilesFromGeoJSON(gjBytes []byte, zoomLevel int) ([]Tile, error) {
fc := gj2.NewFeatureCollection()
if err := json.Unmarshal(gjBytes, fc); err != nil {
return nil, fmt.Errorf("error decoding GeoJSON: %v", err)
}
var tiles []Tile
var tilesAdded int
for _, feature := range fc.Features {
bound := feature.Geometry.Bound()
topLeftLon, topLeftLat := bound.LeftTop().Lon(), bound.LeftTop().Lat()
bottomRightLon, bottomRightLat := bound.RightBottom().Lon(), bound.RightBottom().Lat()
topLeftTile := mercantile.Tile(topLeftLon, topLeftLat, zoomLevel)
bottomRightTile := mercantile.Tile(bottomRightLon, bottomRightLat, zoomLevel)
for x := topLeftTile.X; x <= bottomRightTile.X; x++ {
for y := bottomRightTile.Y; y >= topLeftTile.Y; y-- {
tileID := mercantile.TileID{X: x, Y: y, Z: uint64(zoomLevel)}
center := mercantile.Center(tileID)
if bound.Contains(orb.Point{center[0], center[1]}) {
tiles = append(tiles, Tile{
Tile: tileID,
Lon: center[0],
Lat: center[1],
Index: tilesAdded,
})
tilesAdded++
}
}
}
}
return tiles, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment