return a list of TileInfoScaled objects needed for
		an area of land, with ground_width in meters, and
		width/height in pixels.

		lat/lon is the top left corner. If unspecified, the
		zoom is automatically chosen to avoid having to grow
		the tiles
779448
def area_to_tile_list(self, lat, lon, width, height, ground_width, zoom=None):
		'''
		'''

		pixel_width = ground_width / float(width)
		ground_height = ground_width * (height/(float(width)))
		top_right = mp_util.gps_newpos(lat, lon, 90, ground_width)
		bottom_left = mp_util.gps_newpos(lat, lon, 180, ground_height)
		bottom_right = mp_util.gps_newpos(bottom_left[0], bottom_left[1], 90, ground_width)

		# choose a zoom level if not provided
		if zoom is None:
			zooms = range(self.min_zoom, self.max_zoom+1)
		else:
			zooms = [zoom]
		for zoom in zooms:
			tile_min = self.coord_to_tile(lat, lon, zoom)
			(twidth,theight) = tile_min.size()
			tile_pixel_width = twidth / float(TILES_WIDTH)
			scale = pixel_width / tile_pixel_width
			if scale >= 1.0:
				break

		scaled_tile_width = int(TILES_WIDTH / scale)
		scaled_tile_height = int(TILES_HEIGHT / scale)

		# work out the bottom right tile
		tile_max = self.coord_to_tile(bottom_right[0], bottom_right[1], zoom)

		ofsx = int(tile_min.offsetx / scale)
		ofsy = int(tile_min.offsety / scale)
		srcy = ofsy
		dsty = 0

		ret = []

		# place the tiles
		for y in range(tile_min.y, tile_max.y+1):
			srcx = ofsx
			dstx = 0
			for x in range(tile_min.x, tile_max.x+1):
				if dstx < width and dsty < height:
					ret.append(TileInfoScaled((x,y), zoom, scale,
                                                                  (srcx,srcy), (dstx,dsty), self.service))
				dstx += scaled_tile_width-srcx
				srcx = 0
			dsty += scaled_tile_height-srcy
			srcy = 0
		return ret
1072384
def pixel_coords(latlon, ground_width=0, mt=None, topleft=None, width=None):
    ''''''
    (lat,lon) = (latlon[0], latlon[1])
    return mt.coord_to_pixel(topleft[0], topleft[1], width, ground_width, lat, lon)
417471
def pixels_to_tiles(self, coords, clamp=True):
        
        tile_coords = Vector2()
        tile_coords.X = int(coords[0]) / self.spritesheet[0].width
        tile_coords.Y = int(coords[1]) / self.spritesheet[0].height

        if clamp:
            tile_coords.X, tile_coords.Y = self.clamp_within_range(tile_coords.X, tile_coords.Y)

        return tile_coords
1311402
def area_to_image(self, lat, lon, width, height, ground_width, zoom=None, ordered=True):
		''''''

		img = cv.CreateImage((width,height),8,3)

		tlist = self.area_to_tile_list(lat, lon, width, height, ground_width, zoom)

		# order the display by distance from the middle, so the download happens
		# close to the middle of the image first
		if ordered:
			(midlat, midlon) = self.coord_from_area(width/2, height/2, lat, lon, width, ground_width)
			tlist.sort(key=lambda d: d.distance(midlat, midlon), reverse=True)

		for t in tlist:
			scaled_tile = self.scaled_tile(t)

			w = min(width - t.dstx, scaled_tile.width - t.srcx)
			h = min(height - t.dsty, scaled_tile.height - t.srcy)
			if w > 0 and h > 0:
				cv.SetImageROI(scaled_tile, (t.srcx, t.srcy, w, h))
				cv.SetImageROI(img, (t.dstx, t.dsty, w, h))
				cv.Copy(scaled_tile, img)
				cv.ResetImageROI(img)
				cv.ResetImageROI(scaled_tile)

		# return as an RGB image
		cv.CvtColor(img, img, cv.CV_BGR2RGB)
		return img
1024839
def tiles(ctx, bounds, zoom):
    """"""
    tiles = TilePyramid(
        ctx.obj['grid'],
        tile_size=ctx.obj['tile_size'],
        metatiling=ctx.obj['metatiling']
    ).tiles_from_bounds(bounds, zoom=zoom)
    if ctx.obj['output_format'] == 'Tile':
        for tile in tiles:
            click.echo('%s %s %s' % tile.id)
    elif ctx.obj['output_format'] == 'WKT':
        for tile in tiles:
            click.echo(tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']))
    elif ctx.obj['output_format'] == 'GeoJSON':
        click.echo(
            '{\n'
            '  "type": "FeatureCollection",\n'
            '  "features": ['
        )
        # print tiles as they come and only add comma if there is a next tile
        try:
            tile = next(tiles)
            while True:
                gj = '    %s' % geojson.Feature(
                    geometry=tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']),
                    properties=dict(
                        zoom=tile.zoom,
                        row=tile.row,
                        col=tile.col
                    )
                )
                try:
                    tile = next(tiles)
                    click.echo(gj + ',')
                except StopIteration:
                    click.echo(gj)
                    raise
        except StopIteration:
            pass
        click.echo(
            '  ]\n'
            '}'
        )
782404
def get_surface_boundaries(self):
        
        min_lon, min_lat, max_lon, max_lat = self.get_bounding_box()
        return [[min_lon, max_lon]], [[min_lat, max_lat]]
245225
def area2lonlat(dataarray):
    """"""
    area = dataarray.attrs['area']
    lons, lats = area.get_lonlats_dask()
    lons = xr.DataArray(lons, dims=['y', 'x'],
                        attrs={'name': "longitude",
                               'standard_name': "longitude",
                               'units': 'degrees_east'},
                        name='longitude')
    lats = xr.DataArray(lats, dims=['y', 'x'],
                        attrs={'name': "latitude",
                               'standard_name': "latitude",
                               'units': 'degrees_north'},
                        name='latitude')
    dataarray.attrs['coordinates'] = 'longitude latitude'

    return [dataarray, lons, lats]
299480
private static double[] computeTileEnlargement(double lat, int enlargementInMeter) {
        if (enlargementInMeter == 0) {
            return EPSILON_ZERO;
        }

        double[] epsilons = new double[2];

        epsilons[0] = LatLongUtils.latitudeDistance(enlargementInMeter);
        epsilons[1] = LatLongUtils.longitudeDistance(enlargementInMeter, lat);

        return epsilons;
    }
798343
function(props) {

        var viewSize, wRes, hRes;

        // determine maxResolution
        var maxResolution = props.maxResolution;
        if(props.minScale != null) {
            maxResolution =
                OpenLayers.Util.getResolutionFromScale(props.minScale,
                                                       this.units);
        } else if(maxResolution == "auto" && this.maxExtent != null) {
            viewSize = this.map.getSize();
            wRes = this.maxExtent.getWidth() / viewSize.w;
            hRes = this.maxExtent.getHeight() / viewSize.h;
            maxResolution = Math.max(wRes, hRes);
        }

        // determine minResolution
        var minResolution = props.minResolution;
        if(props.maxScale != null) {
            minResolution =
                OpenLayers.Util.getResolutionFromScale(props.maxScale,
                                                       this.units);
        } else if(props.minResolution == "auto" && this.minExtent != null) {
            viewSize = this.map.getSize();
            wRes = this.minExtent.getWidth() / viewSize.w;
            hRes = this.minExtent.getHeight()/ viewSize.h;
            minResolution = Math.max(wRes, hRes);
        }

        if(typeof maxResolution !== "number" &&
           typeof minResolution !== "number" &&
           this.maxExtent != null) {
            // maxResolution for default grid sets assumes that at zoom
            // level zero, the whole world fits on one tile.
            var tileSize = this.map.getTileSize();
            maxResolution = Math.max(
                this.maxExtent.getWidth() / tileSize.w,
                this.maxExtent.getHeight() / tileSize.h
            );
        }

        // determine numZoomLevels
        var maxZoomLevel = props.maxZoomLevel;
        var numZoomLevels = props.numZoomLevels;
        if(typeof minResolution === "number" &&
           typeof maxResolution === "number" && numZoomLevels === undefined) {
            var ratio = maxResolution / minResolution;
            numZoomLevels = Math.floor(Math.log(ratio) / Math.log(2)) + 1;
        } else if(numZoomLevels === undefined && maxZoomLevel != null) {
            numZoomLevels = maxZoomLevel + 1;
        }

        // are we able to calculate resolutions?
        if(typeof numZoomLevels !== "number" || numZoomLevels <= 0 ||
           (typeof maxResolution !== "number" &&
                typeof minResolution !== "number")) {
            return;
        }

        // now we have numZoomLevels and at least one of maxResolution
        // or minResolution, we can populate the resolutions array

        var resolutions = new Array(numZoomLevels);
        var base = 2;
        if(typeof minResolution == "number" &&
           typeof maxResolution == "number") {
            // if maxResolution and minResolution are set, we calculate
            // the base for exponential scaling that starts at
            // maxResolution and ends at minResolution in numZoomLevels
            // steps.
            base = Math.pow(
                    (maxResolution / minResolution),
                (1 / (numZoomLevels - 1))
            );
        }

        var i;
        if(typeof maxResolution === "number") {
            for(i=0; i<numZoomLevels; i++) {
                resolutions[i] = maxResolution / Math.pow(base, i);
            }
        } else {
            for(i=0; i<numZoomLevels; i++) {
                resolutions[numZoomLevels - 1 - i] =
                    minResolution * Math.pow(base, i);
            }
        }

        return resolutions;
    }
379013
def tile_width(self, zoom):
        
        warnings.warn(DeprecationWarning("tile_width is deprecated"))
        validate_zoom(zoom)
        matrix_pixel = 2**(zoom) * self.tile_size * self.grid.shape.width
        tile_pixel = self.tile_size * self.metatiling
        return matrix_pixel if tile_pixel > matrix_pixel else tile_pixel
37256
def pixel_x_size(self, zoom):
        
        validate_zoom(zoom)
        return round(
            (self.grid.right - self.grid.left) /
            (self.grid.shape.width * 2**zoom * self.tile_size),
            ROUND
        )
1056151
private static Long getApproximateZoomLevel(double[] lengths,
			List<TileMatrix> tileMatrices, double length) {

		Long lengthZoomLevel = null;

		double minLength = lengths[0];
		double maxLength = lengths[lengths.length - 1];

		// Length is zoomed in further than available tiles
		if (length < minLength) {
			double levelsIn = Math.log(length / minLength) / Math.log(.5);
			long zoomAbove = (long) Math.floor(levelsIn);
			long zoomBelow = (long) Math.ceil(levelsIn);
			double lengthAbove = minLength * Math.pow(.5, zoomAbove);
			double lengthBelow = minLength * Math.pow(.5, zoomBelow);
			lengthZoomLevel = tileMatrices.get(tileMatrices.size() - 1)
					.getZoomLevel();
			if (lengthAbove - length <= length - lengthBelow) {
				lengthZoomLevel += zoomAbove;
			} else {
				lengthZoomLevel += zoomBelow;
			}
		}
		// Length is zoomed out further than available tiles
		else if (length > maxLength) {
			double levelsOut = Math.log(length / maxLength) / Math.log(2);
			long zoomAbove = (long) Math.ceil(levelsOut);
			long zoomBelow = (long) Math.floor(levelsOut);
			double lengthAbove = maxLength * Math.pow(2, zoomAbove);
			double lengthBelow = maxLength * Math.pow(2, zoomBelow);
			lengthZoomLevel = tileMatrices.get(0).getZoomLevel();
			if (length - lengthBelow <= lengthAbove - length) {
				lengthZoomLevel -= zoomBelow;
			} else {
				lengthZoomLevel -= zoomAbove;
			}
		}
		// Length is between the available tiles
		else {
			int lengthIndex = Arrays.binarySearch(lengths, length);
			if (lengthIndex < 0) {
				lengthIndex = (lengthIndex + 1) * -1;
			}
			double zoomDistance = Math.log(length / lengths[lengthIndex])
					/ Math.log(.5);
			long zoomLevelAbove = getTileMatrixAtLengthIndex(tileMatrices,
					lengthIndex).getZoomLevel();
			zoomLevelAbove += Math.round(zoomDistance);
			lengthZoomLevel = zoomLevelAbove;
		}

		return lengthZoomLevel;
	}
1220974
def _get_area_def_uniform_sampling(self, lon0, channel):
        """"""
        logger.debug('Computing area definition')

        if lon0 is not None:
            # Define proj4 projection parameters
            proj_dict = {'a': EQUATOR_RADIUS,
                         'b': POLE_RADIUS,
                         'lon_0': lon0,
                         'h': ALTITUDE,
                         'proj': 'geos',
                         'units': 'm'}

            # Calculate maximum scanning angles
            xmax, ymax = get_geostationary_angle_extent(
                namedtuple('area', ['proj_dict'])(proj_dict))

            # Derive area extent using small angle approximation (maximum
            # scanning angle is ~8.6 degrees)
            llx, lly, urx, ury = ALTITUDE * np.array([-xmax, -ymax, xmax, ymax])
            area_extent = [llx, lly, urx, ury]

            # Original image is oversampled. Create pyresample area definition
            # with uniform sampling in N-S and E-W direction
            if self._is_vis(channel):
                sampling = SAMPLING_NS_VIS
            else:
                sampling = SAMPLING_NS_IR
            pix_size = ALTITUDE * sampling
            area_def = pyresample.geometry.AreaDefinition(
                'goes_geos_uniform',
                '{} geostationary projection (uniform sampling)'.format(self.platform_name),
                'goes_geos_uniform',
                proj_dict,
                np.rint((urx - llx) / pix_size).astype(int),
                np.rint((ury - lly) / pix_size).astype(int),
                area_extent)

            return area_def
        else:
            return None
201821
def screen_to_latlon(self, x, y):
        
        xtile = 1. * x / TILE_SIZE + self.xtile
        ytile = 1. * y / TILE_SIZE + self.ytile
        return self.num2deg(xtile, ytile, self.zoom)
106980
def pixel(bounding_box)
      x, y = MapKit.latlng2pixel(@lat, @lng, bounding_box.zoom)
      tile_x, tile_y = MapKit.latlng2pixel(bounding_box.top, bounding_box.left, bounding_box.zoom)
      [x-tile_x, y-tile_y]
    end
1370217
def _global_tiles_from_bounds(tp, bounds, zoom):
    """"""
    seen = set()

    # clip to tilepyramid top and bottom bounds
    left, right = bounds.left, bounds.right
    top = tp.top if bounds.top > tp.top else bounds.top
    bottom = tp.bottom if bounds.bottom < tp.bottom else bounds.bottom

    if left >= tp.left and right <= tp.right:
        for tile in _tiles_from_cleaned_bounds(tp, bounds, zoom):
            yield tile

    # bounds overlap on the Western side with antimeridian
    if left < tp.left:
        for tile in chain(
            # tiles west of antimeridian
            _tiles_from_cleaned_bounds(
                tp,
                Bounds(left + (tp.right - tp.left), bottom, tp.right, top),
                zoom
            ),
            # tiles east of antimeridian
            _tiles_from_cleaned_bounds(
                tp, Bounds(tp.left, bottom, right, top), zoom
            )
        ):
            # make output tiles unique
            if tile.id not in seen:
                seen.add(tile.id)
                yield tile

    # bounds overlap on the Eastern side with antimeridian
    if right > tp.right:
        for tile in chain(
            # tiles west of antimeridian
            _tiles_from_cleaned_bounds(
                tp, Bounds(left, bottom, tp.right, top), zoom
            ),
            # tiles east of antimeridian
            _tiles_from_cleaned_bounds(
                tp,
                Bounds(tp.left, bottom, right - (tp.right - tp.left), top),
                zoom
            )
        ):
            # make output tiles unique
            if tile.id not in seen:
                seen.add(tile.id)
                yield tile
627668
def getMapScale(self, latitude, level, dpi=96):
        '''
        
        '''
        dpm = dpi / 0.0254  # convert to dots per meter
        return self.getGroundResolution(latitude, level) * dpm