Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save wroge/979869ff59046c4d841248c101472783 to your computer and use it in GitHub Desktop.

Select an option

Save wroge/979869ff59046c4d841248c101472783 to your computer and use it in GitHub Desktop.
Web Mercator Tile Conversion
package main
import (
"fmt"
"math"
"github.com/wroge/wgs84"
)
type PixelMercator struct {
A float64
Tile float64
Zoom int
}
func (crs PixelMercator) res0() float64 {
return 2 * math.Pi * crs.A / crs.Tile
}
func (crs PixelMercator) shift() float64 {
return math.Pi * crs.A
}
func (crs PixelMercator) ToWGS84(a, b, c float64) (x0, y0, z0 float64) {
res := crs.res0() / math.Pow(2, float64(crs.Zoom))
north := b*res - crs.shift()
east := a*res - crs.shift()
return wgs84.WebMercator().ToWGS84(east, north, c)
}
func (crs PixelMercator) FromWGS84(x0, y0, z0 float64) (a, b, c float64) {
east, north, h := wgs84.WebMercator().FromWGS84(x0, y0, z0)
res := crs.res0() / math.Pow(2, float64(crs.Zoom))
px := (east + crs.shift()) / res
py := (north + crs.shift()) / res
return px, py, h
}
func (crs PixelMercator) Contains(lon, lat float64) bool {
return true
}
func main() {
lon := 9.0
lat := 52.0
crs := PixelMercator{
A: 6378137.0,
Tile: 256.0,
Zoom: 7,
}
px, py, _ := wgs84.To(crs)(lon, lat, 0)
fmt.Println(px, py)
// 17203.2 21944.235012200952
lon, lat, _ = wgs84.From(crs).Round(3)(px, py, 0)
fmt.Println(lon, lat)
// 9 52
}
@wroge
Copy link
Author

wroge commented Feb 12, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment