主题
TileLayer 继承自: MapLayer, ft.Control, BaseControl
以连续网格形式显示方形栅格图片, 这些图片来源于提供的 url_template 和 fallback_url。
通常,它是添加到 Map 的第一个图层, 因为它提供了其他图层所依托显示的瓦片。
Info: 缓存 该控件支持基本的地图瓦片缓存(适用于兼容的瓦片提供方)。在非 Web 平台上,内置缓存会自动启用,默认软上限为 1 GB。在 Web 平台上,缓存通常由浏览器处理。
对于已缓存瓦片的持久性或可靠性不作任何保证。缓存数据可能随时变得不可用或被清除。例如,在缺失瓦片可能导致风险或不安全状况(如离线或安全关键型地图应用)的场景中,不要依赖此缓存机制。
其设计目标包括:
- 改善开发者体验:
- 通过减少重复的瓦片请求来降低使用瓦片服务器的成本
- 保持应用轻量——内置缓存不附带任何二进制文件或数据库,只是几个你可能已经在用的额外库
- 改善用户体验:
- 缩短瓦片加载时间,因为从缓存获取非常快
- 减少网络/互联网用量,这类用量可能受限或按流量计费/较昂贵(例如移动宽带)
- 通过减轻瓦片服务器的压力来提高对其要求的合规性
- 具备可扩展性、可定制性,并能与多种瓦片提供方集成
但其代价是占用设备上的存储容量。
Info: 支持的来源 flet-map 本身不提供瓦片,所以你需要自备栅格瓦片。支持多种不同的来源。
- Slippy Map/CARTO(XYZ):这是栅格瓦片最常见的格式, 不过许多卫星瓦片会改用 WMS。通常是一个带有 X、Y、Z 占位符的 URL。把
url_template设为瓦片服务器提供的模板—— 通常可以直接从账户门户或文档中复制。额外的信息(如 API/访问密钥)可通过additional_options属性传入。也可以指定一个fallback_url模板,当从主url_template获取瓦片失败时使用。 - 瓦片地图服务(TMS):同样支持。先按上述 XYZ 来源的方法操作,然后把
enable_tms属性设为True。更多关于 TMS 的说明见此处。 - Web 地图服务(WMS):同样支持。使用
wms_configuration指定 WMS 瓦片服务器所需的配置。更多关于 WMS 的说明见此处。
示例:
python
ftm.TileLayer(
url_template="https://tile.openstreetmap.org/{z}/{x}/{y}.png",
user_agent_package_name="MyTownMaps/1.4 (+https://example.org; contact: maps@example.org)",
)属性
| 名称 | 类型 | 默认值 | 说明 |
|---|---|---|---|
url_template | str | required | The URL template is a string that contains placeholders, which, when filled in, create a URL/URI to a specific tile. Provider Examples: https://wiki.openstreetmap.org/wiki/Raster_tile_providers Placeholders: As well as the standard XYZ placeholders in the template, the following placeholders may also be used: - {s}: see subdomains property - {r}: retina scaling factor (2 or 1) - {d}: reflects the tile_size property Additional placeholders can also be added freely to the template, and are filled in with the specified values in additional_options. This can be used to easier add switchable styles or access tokens. Compliance with tile server requirements: It is your own responsibility to comply with any appropriate restrictions and requirements set by your chosen tile server/provider. Always read their terms of service. Failure to do so may lead to any punishment, at the tile server's discretion. Production apps should be extremely cautious about using this tile server; other projects, libraries, and packages suggesting that OpenStreetMap provides free-to-use map tiles are incorrect. Case Example - OpenStreetMap (direct): OpenStreetMap (OSM) is one of the most popular sources for map tiles and data. Their data is free for everyone to use (under ODbL), but their public tile server is not free for everyone to use. It is without cost (for users), but, "without cost" ≠ "without restriction" ≠ "open". Due to excessive usage, the OSM Foundation (running OSM as a not-for-profit) has implemented some measures to prevent abuse and ensure the sustainability of their service. For example: on non-web platforms (ex: desktop), they require a proper User-Agent header to be set. See the user_agent_package_name property for details and recommended best practices. This does not apply to the web platform, because you cannot set a User-Agent header different to what is provided by the browser. Read more on their tile usage policy here. |
fallback_url | Optional[str] | None | Fallback URL template used if fetching tiles from url_template fails. The template must follow the same format and support the same placeholders as url_template. Note: When this is specified, tiles will not be cached in memory, to prevent inconsistencies when url_template is unreliable, avoiding situations where tiles from different sources are displayed simultaneously. Disabling caching may negatively impact performance and efficiency, hence the recommendation to only specify a fallback URL when really necessary. |
subdomains | list[str] | ['a', 'b', 'c']() | List of subdomains used in the URL template. To use subdomains, add the {s} placeholder to the URL template (url_template and fallback_url) Note: Subdomains are now usually considered redundant due to the usage of HTTP/2 & HTTP/3 which don't have the same restrictions. Usage of subdomains will also hinder the ability to cache tiles, potentially leading to increased tile requests and costs. Hence, if the server supports HTTP/2 or HTTP/3 (how to check), avoid using subdomains. Example: If subdomains is set to ["a", "b", "c"] and the url_template is "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", the resulting tile URLs will be: - "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png" - "https://b.tile.openstreetmap.org/{z}/{x}/{y}.png" - "https://c.tile.openstreetmap.org/{z}/{x}/{y}.png" |
user_agent_package_name | str | 'unknown' | The package name of the user agent to use when fetching tiles from the tile server. This is used to identify your app to the tile server, and is important for compliance with tile server usage policies. Tip: OSM best practice recommendations OpenStreetMap (OSM) recommends the following: - Use a clear, unique User-Agent string that names your app and optionally includes a contact URL or email. - Good Example: MyTownMaps/1.4 (+https://example.org; contact: maps@example.org) - Bad Example: com.example.app - For web apps, the browsers will use the browser’s default User-Agent header. - Do not use a library default User-Agent, and never impersonate another app or a browser. - If your platform automatically sets an X-Requested-With header with an app ID, that is acceptable, but a proper User-Agent is still recommended. - Referer (web only): Browsers are expected to send a valid Referer header. Native apps usually do not have a referer, this is ok. |
tile_bounds | Optional[MapLatitudeLongitudeBounds] | None | Defines the bounds of the map. Only tiles that fall within these bounds will be loaded. |
tile_size | int | 256 | The size in pixels of each tile image. Should be a positive power of 2. Note: Some tile servers will use 512x512px tiles instead of 256x256px, such as Mapbox. Using these larger tiles can help reduce tile requests, and when ombined with Retina Mode, it can give the same resolution. To use these tiles, set tile_size to the actual dimensions of the tiles (otherwise they will appear to small), such as 512. Also set zoom_offset to the result of -((d/256) - 1) - ie. -1 for x512px tiles (otherwise they will appear at the wrong geographical locations). The {d} placeholder may also be used in the URL template (url_template and fallback_url) to pass through the value of tile_size. Raises: ValueError: If it is less than 0.0. |
min_native_zoom | int | 0 | Minimum zoom level supported by the tile source. Tiles from below this zoom level will not be displayed, instead tiles at this zoom level will be displayed and scaled. This should usually be 0 (as default), as most tile sources will support zoom levels onwards from this. Raises: ValueError: If it is less than 0.0. |
max_native_zoom | int | 19 | Maximum zoom number supported by the tile source has available. Tiles from above this zoom level will not be displayed, instead tiles at this zoom level will be displayed and scaled. Most tile servers support up to zoom level 19, which is the default. Otherwise, this should be specified. You can also set max_zoom, which is an absolute zoom limit for users. It is recommended to set it to a few levels greater than the maximum zoom level covered by any of your tile layers. Raises: ValueError: If it is less than 0.0. |
zoom_reverse | bool | False | Whether the zoom number used in tile URLs will be reversed (max_zoom - zoom instead of zoom). |
zoom_offset | ft.Number | 0.0 | The zoom number used in tile URLs will be offset with this value. Raises: ValueError: If it is less than 0.0. |
keep_buffer | int | 2 | When panning the map, keep this many rows and columns of tiles before unloading them. |
pan_buffer | int | 1 | When loading tiles only visible tiles are loaded by default. This option increases the loaded tiles by the given number on both axis which can help prevent the user from seeing loading tiles whilst panning. Setting the pan buffer too high can impact performance, typically this is set to 0 or 1. |
enable_tms | bool | False | Whether to inverse Y-axis numbering for tiles. Turn this on for TMS services. |
enable_retina_mode | bool | False | Whether to enable retina mode. Retina mode improves the resolution of map tiles, particularly on high density displays. |
additional_options | dict[str, str] | {} | Static information that should replace placeholders in the url_template. Applying API keys, for example, is a good usecase of this parameter. Example: python TileLayer( url_template="https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}{r}.png?access_token={accessToken}", additional_options={ 'accessToken': '<ACCESS_TOKEN_HERE>', 'id': 'mapbox.streets', }, ) |
max_zoom | ft.Number | float('inf' | The maximum zoom level up to which this layer will be displayed (inclusive). The main usage for this property is to display a different TileLayer when zoomed far in. Prefer max_native_zoom for setting the maximum zoom level supported by the tile source. Typically set to infinity so that there are tiles always displayed. Raises: ValueError: If it is less than 0.0. |
min_zoom | ft.Number | 0.0 | The minimum zoom level at which this layer is displayed (inclusive). Typically 0.0. Raises: ValueError: If it is less than 0.0. |
error_image_src | Optional[str] | None | The source of the tile image to show in place of the tile that failed to load. See on_image_error property for details on the error. |
evict_error_tile_strategy | Optional[TileLayerEvictErrorTileStrategy] | TileLayerEvictErrorTileStrategy.NONE | If a tile was loaded with error, the tile provider will be asked to evict the image 基于 this strategy. |
display_mode | TileDisplay | FadeInTileDisplay(() | Defines how tiles are displayed on the map. |
wms_configuration | Optional[WMSTileLayerConfiguration] | None | The configuration for WMS tile servers. |
expand | Annotated[Optional[Union[bool, int]], V.instance_of((bool, int))] | None | 指定此控件是否/如何扩展以填充父布局中的可用空间。 详见 此处. Note: Has effect only if the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page. Raises: ValueError: If it is not of type bool or int. |
expand_loose | bool | False | 允许控件在主轴方向上有可用空间时扩展,但不要求填满所有可用空间。 详见 此处. Note: 若 expand_loose 为 True,则仅当同时满足以下条件时生效: - expand 不为 None,且 - the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page. |
col | ResponsiveNumber | 12 | 若此控件的父控件是 ResponsiveRow,此属性用于决定该控件横跨多少个虚拟列。 可以是数字,也可以是为不同断点配置不同值的字典,例如 col={"sm": 6}。 0 表示在该断点下隐藏控件,不占用任何列。 默认横跨 12 个虚拟列。 \ |
opacity | Annotated[Number, V.between(0.0, 1.0)] | 1.0 | 定义控件的透明度,取值范围 0.0(完全透明)到 1.0(完全不透明)。 抛出异常:ValueError:若不在 0.0 到 1.0 的闭区间内。 |
tooltip | Optional[TooltipValue] | None | 鼠标悬停时显示的 tooltip。 |
badge | Optional[BadgeValue] | None | 显示在控件顶部的徽标。 |
visible | bool | True | Every control has visible property which is True by default - control is rendered on the page. Setting visible to False 完全阻止该控件(及其所有子控件)渲染到页面画布上. 隐藏的控件不能通过键盘或鼠标聚焦或选中,也不会触发任何事件。 |
disabled | bool | False | Every control has disabled property which is False by default - control and all its children are enabled. Note: The value of this property will be propagated down to all children controls recursively. Example: For example, if you have a form with multiple entry controls you can disable them all together by disabling container: python ft.Column( disabled = True, controls=[ ft.TextField(), ft.TextField() ] ) |
rtl | bool | False | 控件的文字方向是否为从右到左(RTL)。 |
data | Any | skip_ | 任意类型的自定义数据。 |
key | Optional['KeyValue'] | None | 用于在更新之间保持控件身份稳定的 key。 |
只读属性
| 名称 | 类型 | 默认值 | 说明 |
|---|---|---|---|
parent | Optional['BaseControl'] | — | The direct ancestor(parent) of this control. It defaults to None and will only have a value when this control is mounted (added to the page tree). Page 控件(树的根)为例外 —— 它始终 parent=None。 |
page | 'Page' | — | 此控件所属的页面。 |
事件
| 名称 | 类型 | 默认值 | 说明 |
|---|---|---|---|
on_image_error | Optional[ft.ControlEventHandler['TileLayer']] | None | Fires if an error occurs when fetching the tiles. Event handler argument data property contains information about the error. |
方法
| 名称 | 类型 | 默认值 | 说明 |
|---|---|---|---|
before_update | — | — | — |
is_isolated | — | — | Return whether this control is marked as isolated. 被隔离的控件不会参与父级驱动的更新遍历,需要自行管理更新边界。 |
init | — | — | Called after control instance initialization and before the first build / update cycle. 可重写此钩子执行依赖于已初始化字段的轻量设置。 不要在这里调用 update()。 |
build | — | — | 在控件初始化期间调用一次,用于定义其子控件。 page 属性在此方法中可用。 |
before_event | — | — | 在事件处理器执行前拦截事件。 返回 False 取消分发,返回 True 或 None 则继续正常的事件处理。 |
did_mount | — | — | 在控件挂载到页面树之后调用。 可重写以启动需要已挂载页面的资源,例如订阅、定时器或服务监听。 |
will_unmount | — | — | 在控件从页面树移除之前调用。 可重写以释放 did_mount() 中创建的资源,例如订阅、定时器或外部句柄。 |
get_data_channel | — | — | Resolve the [DataChannel] allocated on the Dart side for this widget. Pattern: on_data_channel_open: Optional[ft.EventHandler[DataChannelOpenEvent]] = None def init(self): self.on_data_channel_open = self._on_open def _on_open(self, e): self._channel = self.get_data_channel(e.channel_id) Idempotent — the underlying Connection caches DataChannels by id, so repeated calls return the same instance. No error path: the id always comes from a framework-fired event, so by the time this runs the channel exists on both sides. |
update | None | — | 请求更新该控件的 UI。 在修改控件状态或属性后调用。 控件必须已挂载到页面,并且未被冻结。 |