nigig-org/crates/apps/map/API.md
andodeki d4496136f6 docs(map): add comprehensive documentation for map crate (Phase 5)
Add comprehensive documentation for the nigig-map crate:

README.md:
- Overview and features
- Architecture overview
- Basic usage examples
- API reference summary
- Performance information
- Testing instructions

API.md:
- Complete API reference
- All types, methods, and functions documented
- Code examples for each API
- Constants and error types documented

USER_GUIDE.md:
- Getting started guide
- Basic usage instructions
- Offline maps (MBTiles) guide
- Online maps (Overpass API) guide
- Style customization guide
- Programmatic control examples
- Performance tuning tips
- Troubleshooting guide
- Complete examples

This completes Phase 5: Documentation
2026-07-28 17:22:32 +00:00

1001 lines
19 KiB
Markdown

# Nigig Map API Reference
Complete API reference for the Nigig Map crate.
## Modules
### nigig_map
Main module containing the map widget and related types.
#### Re-exports
```rust
pub use makepad_fast_inflate;
pub use makepad_mbtile_reader;
```
#### Submodules
- `geometry` - Geometry types and transformations
- `label` - Label extraction and placement
- `label_state` - Label placement state
- `renderer` - Rendering logic
- `render_graph` - Render graph execution
- `scheduler` - Tile loading scheduler
- `sprite` - Sprite rendering
- `style` - Style compilation
- `tile` - Tile types
- `tile_decode` - Tile decoding
- `tile_disk` - Disk cache
- `viewport` - Viewport state
- `mvt_parser` - MVT tile parsing
- `overpass_parser` - Overpass API parsing
- `asset_loader` - Asset loading
## Types
### MapView
Main map widget for rendering maps.
```rust
#[derive(Script, Widget)]
pub struct MapView {
// ... fields ...
}
```
#### Properties
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `center_lon` | `f64` | 4.9041 | Center longitude |
| `center_lat` | `f64` | 52.3676 | Center latitude |
| `zoom` | `f64` | 14.0 | Zoom level |
| `min_zoom` | `f64` | 11.0 | Minimum zoom level |
| `max_zoom` | `f64` | 17.0 | Maximum zoom level |
| `dark_theme` | `bool` | false | Use dark theme |
| `use_network` | `bool` | true | Enable network requests |
| `use_local_mbtiles` | `bool` | true | Use local MBTiles |
| `local_mbtiles_path` | `String` | "local/mbtiles/kenya-shortbread-1.0.mbtiles" | Path to MBTiles file |
| `local_tile_cache_dir` | `String` | "local/tilecache_v5" | Path to tile cache directory |
| `style_light` | `MapThemeStyle` | (default) | Light theme style |
| `style_dark` | `MapThemeStyle` | (default) | Dark theme style |
#### Methods
##### `load_style_json`
Load style from JSON string.
```rust
pub fn load_style_json(&mut self, json_str: &str) -> Result<(), String>
```
**Parameters:**
- `json_str` - JSON string containing Mapbox GL style
**Returns:**
- `Ok(())` on success
- `Err(String)` on error
**Example:**
```rust
let style_json = r#"{"version": 8, "sources": {...}, "layers": [...]}"#;
map_view.load_style_json(style_json)?;
```
##### `recompile_style_for_zoom`
Recompile style for specific zoom level.
```rust
pub fn recompile_style_for_zoom(&mut self, zoom: f64)
```
**Parameters:**
- `zoom` - Zoom level to compile for
**Example:**
```rust
map_view.recompile_style_for_zoom(14.0);
```
##### `render_graph`
Get reference to render graph.
```rust
pub fn render_graph(&self) -> &RenderGraph
```
**Returns:**
- Reference to `RenderGraph`
**Example:**
```rust
let graph = map_view.render_graph();
println!("Number of passes: {}", graph.passes().len());
```
##### `enable_pass`
Enable a render pass.
```rust
pub fn enable_pass(&mut self, pass_type: PassType)
```
**Parameters:**
- `pass_type` - Pass type to enable
**Example:**
```rust
map_view.enable_pass(PassType::Label);
```
##### `disable_pass`
Disable a render pass.
```rust
pub fn disable_pass(&mut self, pass_type: PassType)
```
**Parameters:**
- `pass_type` - Pass type to disable
**Example:**
```rust
map_view.disable_pass(PassType::POI);
```
##### `set_pass_zoom_range`
Set zoom range for a render pass.
```rust
pub fn set_pass_zoom_range(&mut self, pass_type: PassType, min_zoom: f64, max_zoom: f64)
```
**Parameters:**
- `pass_type` - Pass type to configure
- `min_zoom` - Minimum zoom level (inclusive)
- `max_zoom` - Maximum zoom level (inclusive)
**Example:**
```rust
map_view.set_pass_zoom_range(PassType::Label, 14.0, 20.0);
```
### MapThemeStyle
Style configuration for map rendering.
```rust
#[derive(Script, ScriptHook, Clone, Default)]
pub struct MapThemeStyle {
pub background: Vec4f,
pub label: Vec4f,
pub status_text: Vec4f,
pub fill_rules: Vec<MapFillRule>,
pub road_rules: Vec<MapRoadRule>,
pub waterway_rules: Vec<MapWaterwayRule>,
pub rail_rules: Vec<MapRailRule>,
}
```
#### Properties
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `background` | `Vec4f` | #xddd7cc | Background color |
| `label` | `Vec4f` | #x000000 | Label color |
| `status_text` | `Vec4f` | #xdee9f4 | Status text color |
| `fill_rules` | `Vec<MapFillRule>` | [] | Fill rules |
| `road_rules` | `Vec<MapRoadRule>` | [] | Road rules |
| `waterway_rules` | `Vec<MapWaterwayRule>` | [] | Waterway rules |
| `rail_rules` | `Vec<MapRailRule>` | [] | Rail rules |
### MapFillRule
Fill rule for polygon features.
```rust
#[derive(Script, ScriptHook, Clone, Default)]
pub struct MapFillRule {
pub group: String,
pub value: String,
pub color: Vec4f,
}
```
#### Properties
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `group` | `String` | "" | Feature group (e.g., "building", "water") |
| `value` | `String` | "" | Feature value (e.g., "residential", "yes") |
| `color` | `Vec4f` | #x000000 | Fill color |
**Example:**
```rust
MapFillRule {
group: "building",
value: "yes",
color: #xd7dee7,
}
```
### MapRoadRule
Road rendering rule.
```rust
#[derive(Script, ScriptHook, Clone, Default)]
pub struct MapRoadRule {
pub kind: String,
pub sort_rank: i32,
pub casing_color: Vec4f,
pub casing_width: f32,
pub casing_shape_id: f32,
pub center_color: Vec4f,
pub center_width: f32,
pub center_shape_id: f32,
}
```
#### Properties
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `kind` | `String` | "" | Road kind (e.g., "motorway", "primary") |
| `sort_rank` | `i32` | 0 | Sort rank (higher = drawn on top) |
| `casing_color` | `Vec4f` | #x000000 | Casing color |
| `casing_width` | `f32` | 0.0 | Casing width |
| `casing_shape_id` | `f32` | 0.0 | Casing shape ID |
| `center_color` | `Vec4f` | #x000000 | Center color |
| `center_width` | `f32` | 0.0 | Center width |
| `center_shape_id` | `f32` | 0.0 | Center shape ID |
**Example:**
```rust
MapRoadRule {
kind: "motorway",
sort_rank: 700,
casing_color: #xc1782f,
casing_width: 6.2,
casing_shape_id: 0.0,
center_color: #xffc266,
center_width: 4.2,
center_shape_id: 0.0,
}
```
### MapWaterwayRule
Waterway rendering rule.
```rust
#[derive(Script, ScriptHook, Clone, Default)]
pub struct MapWaterwayRule {
pub kind: String,
pub sort_rank: i32,
pub casing_color: Vec4f,
pub casing_width: f32,
pub casing_shape_id: f32,
pub center_color: Vec4f,
pub center_width: f32,
pub center_shape_id: f32,
}
```
#### Properties
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `kind` | `String` | "" | Waterway kind (e.g., "river", "stream") |
| `sort_rank` | `i32` | 0 | Sort rank (higher = drawn on top) |
| `casing_color` | `Vec4f` | #x000000 | Casing color |
| `casing_width` | `f32` | 0.0 | Casing width |
| `casing_shape_id` | `f32` | 0.0 | Casing shape ID |
| `center_color` | `Vec4f` | #x000000 | Center color |
| `center_width` | `f32` | 0.0 | Center width |
| `center_shape_id` | `f32` | 0.0 | Center shape ID |
### MapRailRule
Rail rendering rule.
```rust
#[derive(Script, ScriptHook, Clone, Default)]
pub struct MapRailRule {
pub sort_rank: i32,
pub casing_color: Vec4f,
pub casing_width: f32,
pub casing_shape_id: f32,
pub center_color: Vec4f,
pub center_width: f32,
pub center_shape_id: f32,
}
```
#### Properties
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `sort_rank` | `i32` | 0 | Sort rank (higher = drawn on top) |
| `casing_color` | `Vec4f` | #x000000 | Casing color |
| `casing_width` | `f32` | 0.0 | Casing width |
| `casing_shape_id` | `f32` | 0.0 | Casing shape ID |
| `center_color` | `Vec4f` | #x000000 | Center color |
| `center_width` | `f32` | 0.0 | Center width |
| `center_shape_id` | `f32` | 0.0 | Center shape ID |
### PassType
Render pass types.
```rust
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PassType {
Fill,
Stroke,
Label,
POI,
}
```
#### Variants
- `Fill` - Fill pass (polygons)
- `Stroke` - Stroke pass (lines)
- `Label` - Label pass (text)
- `POI` - POI pass (points of interest)
### TileKey
Tile key for identifying tiles.
```rust
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct TileKey {
pub z: u32,
pub x: u32,
pub y: u32,
}
```
#### Properties
| Property | Type | Description |
|----------|------|-------------|
| `z` | `u32` | Zoom level |
| `x` | `u32` | X coordinate |
| `y` | `u32` | Y coordinate |
### TileLoadState
Tile loading state.
```rust
#[derive(Debug)]
pub enum TileLoadState {
Loading,
Ready {
fill_geometry: Option<Geometry>,
stroke_geometry: Option<Geometry>,
feature_count: usize,
labels: Vec<TileLabel>,
pois: Vec<PoiFeature>,
},
Failed {
error: String,
},
}
```
#### Variants
- `Loading` - Tile is being loaded
- `Ready` - Tile is ready with geometry and labels
- `Failed` - Tile failed to load
### TileEntry
Tile entry in cache.
```rust
pub struct TileEntry {
pub state: TileLoadState,
pub last_used: u64,
pub attempts: u8,
}
```
#### Properties
| Property | Type | Description |
|----------|------|-------------|
| `state` | `TileLoadState` | Tile loading state |
| `last_used` | `u64` | Last used timestamp |
| `attempts` | `u8` | Number of load attempts |
### RenderGraph
Render graph for managing render passes.
```rust
pub struct RenderGraph {
passes: Vec<RenderPass>,
}
```
#### Methods
##### `passes`
Get list of render passes.
```rust
pub fn passes(&self) -> &[RenderPass]
```
**Returns:**
- Slice of render passes
### ViewportState
Viewport state for managing view transformations.
```rust
pub struct ViewportState {
pub center: Vec2d,
pub zoom: f64,
pub min_zoom: f64,
pub max_zoom: f64,
pub rotation: f64,
}
```
#### Properties
| Property | Type | Description |
|----------|------|-------------|
| `center` | `Vec2d` | Center coordinates |
| `zoom` | `f64` | Zoom level |
| `min_zoom` | `f64` | Minimum zoom level |
| `max_zoom` | `f64` | Maximum zoom level |
| `rotation` | `f64` | Rotation angle |
#### Methods
##### `view_zoom`
Get clamped zoom level.
```rust
pub fn view_zoom(&self) -> f64
```
**Returns:**
- Clamped zoom level
##### `world_size`
Get world size at current zoom.
```rust
pub fn world_size(&self) -> f64
```
**Returns:**
- World size in pixels
##### `center_world`
Get center in world coordinates.
```rust
pub fn center_world(&self) -> Vec2d
```
**Returns:**
- Center in world coordinates
##### `map_offset`
Get map offset for rendering.
```rust
pub fn map_offset(&self) -> Vec2f
```
**Returns:**
- Map offset in pixels
##### `apply_pinch`
Apply pinch gesture.
```rust
pub fn apply_pinch(
&mut self,
initial_zoom: f64,
initial_center: Vec2d,
initial_distance: f64,
current_distance: f64,
midpoint: Vec2d,
)
```
**Parameters:**
- `initial_zoom` - Initial zoom level
- `initial_center` - Initial center
- `initial_distance` - Initial pinch distance
- `current_distance` - Current pinch distance
- `midpoint` - Pinch midpoint
##### `apply_scroll`
Apply scroll gesture.
```rust
pub fn apply_scroll(&mut self, scroll: f64, anchor: Vec2d)
```
**Parameters:**
- `scroll` - Scroll amount
- `anchor` - Scroll anchor point
##### `visible_tile_keys`
Get visible tile keys.
```rust
pub fn visible_tile_keys(&self) -> Vec<TileKey>
```
**Returns:**
- List of visible tile keys
### TileCache
Tile cache for storing loaded tiles.
```rust
pub struct TileCache {
tiles: HashMap<TileKey, TileEntry>,
max_tiles: usize,
frame_counter: u64,
}
```
#### Methods
##### `get`
Get tile from cache.
```rust
pub fn get(&self, key: TileKey) -> Option<&TileEntry>
```
**Parameters:**
- `key` - Tile key
**Returns:**
- Tile entry if found
##### `insert_loading`
Insert tile as loading.
```rust
pub fn insert_loading(&mut self, key: TileKey, state: TileLoadState)
```
**Parameters:**
- `key` - Tile key
- `state` - Tile load state
##### `insert_ready`
Insert tile as ready.
```rust
pub fn insert_ready(&mut self, cx: &mut Cx, key: TileKey, buffers: TileBuffers)
```
**Parameters:**
- `cx` - Makepad context
- `key` - Tile key
- `buffers` - Tile buffers
##### `mark_failed`
Mark tile as failed.
```rust
pub fn mark_failed(&mut self, key: TileKey, error: String)
```
**Parameters:**
- `key` - Tile key
- `error` - Error message
##### `evict`
Evict tiles from cache.
```rust
pub fn evict(&mut self, cx: &mut Cx, visible: &HashSet<TileKey>, target_zoom: u32)
```
**Parameters:**
- `cx` - Makepad context
- `visible` - Visible tile keys
- `target_zoom` - Target zoom level
### TileScheduler
Tile loading scheduler.
```rust
pub struct TileScheduler {
visible_tiles: Vec<TileKey>,
pending_tiles: HashSet<TileKey>,
current_generation: u64,
}
```
#### Methods
##### `schedule`
Schedule tile loading.
```rust
pub fn schedule(
&mut self,
cache: &TileCache,
config: &SchedulerConfig,
style_epoch: u64,
) -> Vec<TileAction>
```
**Parameters:**
- `cache` - Tile cache
- `config` - Scheduler configuration
- `style_epoch` - Style epoch
**Returns:**
- List of tile actions
##### `update_visible`
Update visible tiles.
```rust
pub fn update_visible(&mut self, viewport: &mut ViewportState) -> bool
```
**Parameters:**
- `viewport` - Viewport state
**Returns:**
- True if visible tiles changed
### SchedulerConfig
Scheduler configuration.
```rust
pub struct SchedulerConfig {
pub use_network: bool,
pub use_local_mbtiles: bool,
pub max_pending_requests: usize,
pub max_local_tile_batch: usize,
pub max_tile_retries: u8,
pub local_mbtiles_path: String,
pub local_tile_cache_dir: String,
}
```
#### Properties
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `use_network` | `bool` | true | Enable network requests |
| `use_local_mbtiles` | `bool` | true | Use local MBTiles |
| `max_pending_requests` | `usize` | 6 | Maximum pending requests |
| `max_local_tile_batch` | `usize` | 10 | Maximum local tile batch size |
| `max_tile_retries` | `u8` | 3 | Maximum tile retries |
| `local_mbtiles_path` | `String` | "local/mbtiles/kenya-shortbread-1.0.mbtiles" | Path to MBTiles file |
| `local_tile_cache_dir` | `String` | "local/tilecache_v5" | Path to tile cache directory |
### TileAction
Tile loading action.
```rust
pub enum TileAction {
LoadLocalBatch {
mbtiles_path: PathBuf,
cache_dir: String,
requested: Vec<TileKey>,
style_epoch: u64,
generation: u64,
},
LoadFromDiskCache {
tile_key: TileKey,
cache_path: PathBuf,
style_epoch: u64,
generation: u64,
},
LoadFromNetwork {
request_id: LiveId,
http_request: HttpRequest,
tile_key: TileKey,
generation: u64,
},
Nothing,
}
```
#### Variants
- `LoadLocalBatch` - Load batch of tiles from local MBTiles
- `LoadFromDiskCache` - Load tile from disk cache
- `LoadFromNetwork` - Load tile from network
- `Nothing` - No action
## Functions
### Geometry Functions
#### `lon_lat_to_normalized`
Convert lon/lat to normalized coordinates.
```rust
pub fn lon_lat_to_normalized(lon: f64, lat: f64) -> Vec2d
```
**Parameters:**
- `lon` - Longitude
- `lat` - Latitude
**Returns:**
- Normalized coordinates (0-1)
#### `normalized_to_lon_lat`
Convert normalized coordinates to lon/lat.
```rust
pub fn normalized_to_lon_lat(normalized: Vec2d) -> (f64, f64)
```
**Parameters:**
- `normalized` - Normalized coordinates (0-1)
**Returns:**
- (longitude, latitude)
#### `tile_world_size_zoom`
Get tile world size at zoom level.
```rust
pub fn tile_world_size_zoom(zoom: f64) -> f64
```
**Parameters:**
- `zoom` - Zoom level
**Returns:**
- Tile world size in pixels
### Style Functions
#### `fill_color_for_tags`
Get fill color for tags.
```rust
pub fn fill_color_for_tags(
tags: &HashMap<String, String>,
theme: &CompiledMapTheme,
) -> Option<u32>
```
**Parameters:**
- `tags` - Feature tags
- `theme` - Compiled theme
**Returns:**
- Fill color if found
#### `stroke_style_for_tags`
Get stroke style for tags.
```rust
pub fn stroke_style_for_tags(
tags: &HashMap<String, String>,
theme: &CompiledMapTheme,
zoom: u32,
) -> Option<StrokeStyle>
```
**Parameters:**
- `tags` - Feature tags
- `theme` - Compiled theme
- `zoom` - Zoom level
**Returns:**
- Stroke style if found
### Label Functions
#### `extract_way_label`
Extract label from way.
```rust
pub fn extract_way_label(
tags: &HashMap<String, String>,
points: &[(f32, f32)],
) -> Option<TileLabel>
```
**Parameters:**
- `tags` - Way tags
- `points` - Way points
**Returns:**
- Tile label if found
#### `get_label_priority`
Get label priority.
```rust
pub fn get_label_priority(tags: &HashMap<String, String>) -> i32
```
**Parameters:**
- `tags` - Feature tags
**Returns:**
- Label priority
### MVT Parser Functions
#### `decode_vector_tile_payload`
Decode vector tile payload.
```rust
pub fn decode_vector_tile_payload(raw: &[u8]) -> Result<Vec<u8>, String>
```
**Parameters:**
- `raw` - Raw tile data
**Returns:**
- Decoded tile data or error
#### `parse_mvt_tile`
Parse MVT tile.
```rust
pub fn parse_mvt_tile(
tile_data: &[u8],
tile_key: TileKey,
builder: &mut MvtTileJsonBuilder,
) -> Result<(), String>
```
**Parameters:**
- `tile_data` - Tile data
- `tile_key` - Tile key
- `builder` - MVT tile JSON builder
**Returns:**
- Ok(()) on success or error
### Overpass Parser Functions
#### `build_tile_buffers_from_body`
Build tile buffers from Overpass response body.
```rust
pub fn build_tile_buffers_from_body(
tile_key: TileKey,
body: &str,
theme: &CompiledMapTheme,
) -> Result<TileBuffers, String>
```
**Parameters:**
- `tile_key` - Tile key
- `body` - Overpass response body
- `theme` - Compiled theme
**Returns:**
- Tile buffers or error
#### `mbtiles_tile_to_overpass_response`
Convert MBTiles tile to Overpass response.
```rust
pub fn mbtiles_tile_to_overpass_response(
tile_key: TileKey,
raw_tile_data: &[u8],
) -> Result<OverpassResponse, String>
```
**Parameters:**
- `tile_key` - Tile key
- `raw_tile_data` - Raw tile data
**Returns:**
- Overpass response or error
## Constants
### Tile Constants
```rust
pub const TILE_SIZE: f64 = 256.0;
pub const TILE_SIZE_U32: u32 = 256;
pub const TILE_BUFFER_SIZE: usize = 8;
```
### Label Constants
```rust
pub const LABEL_PLACEMENT_MAX_ITERATIONS: usize = 100;
pub const LABEL_COLLISION_PADDING: f32 = 2.0;
pub const LABEL_MIN_DISTANCE: f32 = 10.0;
```
### Style Constants
```rust
pub const STYLE_MAX_ZOOM: u32 = 22;
pub const STYLE_MIN_ZOOM: u32 = 0;
```
## Error Types
### ParseError
Error type for parsing errors.
```rust
#[derive(Debug)]
pub enum ParseError {
InvalidFormat(String),
InvalidData(String),
IoError(std::io::Error),
}
```
#### Variants
- `InvalidFormat` - Invalid format error
- `InvalidData` - Invalid data error
- `IoError` - I/O error
## See Also
- [README.md](README.md) - Main documentation
- [ARCHITECTURE.md](ARCHITECTURE.md) - Architecture documentation
- [USER_GUIDE.md](USER_GUIDE.md) - User guide