// Take the list of station locations and fold them into the regions of a grid. func BuildGrid(locs []*StationLoc, zips []*Zip, r image.Rectangle, c *GridConfig) *Grid { nx, ny := c.W, c.H regs := make([][]*Region, nx) for i := 0; i < nx; i++ { regs[i] = make([]*Region, ny) } // create all active rectangles for _, xy := range c.Active { i, j := xy[0], xy[1] regs[i][j] = &Region{ I: i, J: j, Rect: image.Rect(i*c.Size, j*c.Size, (i+1)*c.Size, (j+1)*c.Size), } } // assign stations to their region for _, loc := range locs { ix, iy := int(loc.X/float64(c.Size)), int(loc.Y/float64(c.Size)) r := regs[ix][iy] if r == nil { continue } r.Stations = append(r.Stations, loc) } // assign zips to their region for _, zip := range zips { ix, iy := int(zip.X/float64(c.Size)), int(zip.Y/float64(c.Size)) if ix >= c.W || ix < 0 || iy >= c.H || iy < 0 { continue } r := regs[ix][iy] if r == nil { continue } r.Zips = append(r.Zips, zip) } grid := &Grid{ W: nx, H: ny, Grid: regs, } for _, xy := range c.Active { i, j := xy[0], xy[1] regs[i][j].Nearest = NearestN(c, grid, regs[i][j], 20) city := LabelFor(grid, i, j) regs[i][j].City = city } return grid }