Last active
October 8, 2022 03:32
-
-
Save wroge/979869ff59046c4d841248c101472783 to your computer and use it in GitHub Desktop.
Web Mercator Tile Conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://go.dev/play/p/zzg8uVSsJVI