### Minimal MapView Setup with Markers
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/00_START_HERE.md
Demonstrates the basic setup of the MapView component with initial region and a few markers. Ensure you have react-native-maps installed.
```typescript
import MapView from "react-native-map-clustering";
import { Marker } from "react-native-maps";
```
--------------------------------
### Import Path Guide
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Guide on how to import components and types from the library.
```JavaScript
import MapView, { Marker, PROVIDER_GOOGLE } from 'react-native-maps';
import { EdgePadding, Region } from './types'; // Assuming types are in a local file
import { SuperCluster } from './supercluster'; // Example internal import
```
--------------------------------
### Advanced Usage Patterns
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Guides and examples for advanced integration scenarios, including SuperCluster integration, custom styling, and performance optimization.
```APIDOC
## Advanced Usage
### Description
Explores advanced patterns and techniques for integrating and customizing the map clustering functionality.
### Endpoint
`ADVANCED_USAGE.md`
### Patterns
- **SuperCluster Integration**: Examples of directly using the `SuperCluster` engine for custom clustering logic.
- **Custom Cluster Styling**: Demonstrations of how to style clusters using custom render functions or components.
- **Marker Metadata**: Patterns for associating and displaying metadata with individual markers.
- **Filtering & Dynamic Updates**: Techniques for filtering markers and dynamically updating the map display.
- **Animation & Pan/Zoom Control**: Examples of integrating animations and controlling map interactions.
- **State Management**: Strategies for managing map state using Redux or Context API.
- **Performance Optimization**: Best practices for optimizing performance with large datasets.
- **Troubleshooting**: Common issues and their solutions.
```
--------------------------------
### Full Example Usage of Map Clustering
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/README.md
Demonstrates how to integrate react-native-map-clustering into a React Native application. This example shows setting up the MapView with initial region and adding multiple markers that will be clustered.
```javascript
import React from "react";
import MapView from "react-native-map-clustering";
import { Marker } from "react-native-maps";
const INITIAL_REGION = {
latitude: 52.5,
longitude: 19.2,
latitudeDelta: 8.5,
longitudeDelta: 8.5,
};
const App = () => (
);
export default App;
```
--------------------------------
### Custom Cluster Styling Example
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Provides an example of custom cluster styling using the `renderCluster` prop.
```JavaScript
import MapView, { Marker } from 'react-native-maps';
const MyCustomCluster = ({ points }) => (
{points.length}
);
{/* Markers go here */}
const styles = StyleSheet.create({
cluster: {
width: 40,
height: 40,
borderRadius: 20,
backgroundColor: 'rgba(0, 122, 255, 0.8)',
justifyContent: 'center',
alignItems: 'center'
},
clusterText: {
color: 'white',
fontWeight: 'bold'
}
});
```
--------------------------------
### Get Cluster Expansion Zoom Example
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/EVENTS_AND_CALLBACKS.md
An example of how to use the getClusterExpansionZoom method within a cluster press handler to determine the zoom level required to expand a cluster.
```typescript
const handleClusterPress = (cluster, markers) => {
if (superClusterRef.current) {
const expansion = superClusterRef.current.getClusterExpansionZoom(cluster.id);
console.log(`Zoom to ${expansion} to expand cluster`);
}
};
```
--------------------------------
### Example usage of calculateBBox
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/api-reference/helpers.md
Shows how to use `calculateBBox` with a sample region to obtain a bounding box array.
```typescript
import { calculateBBox } from "react-native-map-clustering/lib/helpers";
const region = {
latitude: 52.5,
longitude: 19.2,
latitudeDelta: 8.5,
longitudeDelta: 8.5,
};
const bbox = calculateBBox(region);
// Returns: [10.7, 44, 27.7, 61] (approximately)
```
--------------------------------
### Animation and Pan/Zoom Control Example
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Shows how to animate marker movements and control map panning/zooming.
```JavaScript
const mapRef = useRef(null);
const animateToLocation = (lat, lon) => {
mapRef.current.animateToRegion({
latitude: lat,
longitude: lon,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}, 1000); // Duration in ms
};
animateToLocation(37.78825, -122.4324)} />
```
--------------------------------
### Marker Metadata Example
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Shows how to associate metadata with markers for custom display or interaction.
```JavaScript
const markers = [
{
coordinate: { latitude: 37.78825, longitude: -122.4324 },
title: 'Marker 1',
description: 'This is the first marker',
metadata: { id: 'm1', type: 'restaurant' } // Custom metadata
},
// ... more markers
];
{markers.map(marker => (
))}
```
--------------------------------
### Basic MapView Usage
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/api-reference/MapView.md
Demonstrates the basic setup for using the MapView component with initial region and markers. Ensure necessary imports are included.
```typescript
import React from "react";
import MapView from "react-native-map-clustering";
import { Marker } from "react-native-maps";
const INITIAL_REGION = {
latitude: 52.5,
longitude: 19.2,
latitudeDelta: 8.5,
longitudeDelta: 8.5,
};
export default function App() {
return (
);
}
```
--------------------------------
### Install react-native-map-clustering and react-native-maps
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/README.md
Install the necessary packages using npm or yarn. Ensure both react-native-map-clustering and react-native-maps are included.
```bash
npm install react-native-map-clustering react-native-maps --save
// yarn add react-native-map-clustering react-native-maps
```
--------------------------------
### Filtering and Dynamic Updates Example
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Demonstrates filtering markers dynamically based on certain criteria.
```JavaScript
const [allMarkers, setAllMarkers] = useState(initialMarkers);
const [filteredMarkers, setFilteredMarkers] = useState(initialMarkers);
const filterByType = (type) => {
const filtered = allMarkers.filter(marker => marker.metadata.type === type);
setFilteredMarkers(filtered);
};
// In your MapView component:
{filteredMarkers.map(marker => (
))}
// Button to trigger filter
filterByType('restaurant')} />
```
--------------------------------
### Example usage of returnMapZoom
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/api-reference/helpers.md
Demonstrates calculating the map zoom level using `returnMapZoom` after obtaining a bounding box with `calculateBBox`.
```typescript
import { returnMapZoom, calculateBBox } from "react-native-map-clustering/lib/helpers";
const region = {
latitude: 52.5,
longitude: 19.2,
latitudeDelta: 8.5,
longitudeDelta: 8.5,
};
const bbox = calculateBBox(region);
const zoom = returnMapZoom(region, bbox, 1);
console.log(zoom); // e.g., 7
```
--------------------------------
### Custom Cluster Marker Example
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/api-reference/ClusteredMarker.md
An example demonstrating how to create a custom cluster marker by referencing the structure of the internal ClusteredMarker component. This custom component can be used with the MapView's renderCluster prop.
```typescript
import { Marker } from "react-native-maps";
import { Text, View, StyleSheet, TouchableOpacity } from "react-native";
// Example custom cluster marker
const CustomClusterMarker = ({
geometry,
properties,
onPress,
clusterColor,
clusterTextColor,
}) => {
const [lng, lat] = geometry.coordinates;
const count = properties.point_count;
return (
{count}
);
};
const styles = StyleSheet.create({
container: {
width: 60,
height: 60,
justifyContent: "center",
alignItems: "center",
},
cluster: {
justifyContent: "center",
alignItems: "center",
},
text: {
fontWeight: "bold",
fontSize: 17,
},
});
```
--------------------------------
### Basic MapView Usage
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/QUICK_REFERENCE.md
Render a MapView with initial region and add markers. This is the fundamental setup for using the clustering library.
```typescript
```
--------------------------------
### Example usage of isMarker
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/api-reference/helpers.md
Demonstrates how to use the `isMarker` function with a standard Marker and one explicitly excluded from clustering.
```typescript
import { isMarker } from "react-native-map-clustering/lib/helpers";
import { Marker } from "react-native-maps";
const element = ;
console.log(isMarker(element)); // true
const excluded = ;
console.log(isMarker(excluded)); // false
```
--------------------------------
### Direct SuperCluster Integration Setup
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/ADVANCED_USAGE.md
Access the SuperCluster instance to call methods directly for fine-grained control. Import MapView and useRef, then initialize refs for the map and SuperCluster.
```typescript
import MapView from "react-native-map-clustering";
import { useRef } from "react";
const mapRef = useRef();
const superClusterRef = useRef();
// Now you can call SuperCluster methods directly
const getClusterChildren = (clusterId) => {
const leaves = superClusterRef.current?.getLeaves(clusterId, Infinity);
return leaves;
};
```
--------------------------------
### Component Props Reference
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Detailed documentation for all props available on the MapView component, including their types, default values, and usage examples.
```APIDOC
## MapView Component Props
### Description
Provides a comprehensive list of all configurable props for the `MapView` component, enabling detailed control over map clustering behavior.
### Endpoint
`api-reference/MapView.md`
### Parameters
#### Props
- **`clusteringEnabled`** (boolean) - Optional - Enables or disables marker clustering.
- **`clusterOptions`** (object) - Optional - Configuration object for clustering behavior. See `configuration.md` for details.
- **`data`** (array) - Required - Array of markers to be displayed on the map.
- **`onClusterPress`** (function) - Optional - Callback function executed when a cluster is pressed.
- **`onMarkerPress`** (function) - Optional - Callback function executed when a marker is pressed.
### Request Example
```javascript
```
### Response
#### Success Response (N/A)
This component does not return a direct response. Its effects are visual on the map.
#### Response Example (N/A)
N/A
```
--------------------------------
### Type Usage in Application Code
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/types.md
Demonstrates how to import and use the MapView component with type annotations for refs and callbacks. Includes example props and a basic Marker.
```typescript
import MapView from "react-native-map-clustering";
import { Marker } from "react-native-maps";
import { useRef } from "react";
// Type the ref
const superClusterRef = useRef(null);
// Type the callbacks
const handleClusterPress = (cluster: any, markers?: any[]) => {
console.log(`Cluster has ${markers?.length} markers`);
};
const handleRegionChange = (region: any, details: any, markers?: any[]) => {
console.log(`Region: ${region.latitude}, ${region.longitude}`);
};
const handleMarkersChange = (markers?: any[]) => {
console.log(`Visible markers: ${markers?.length}`);
};
// Use in component
```
--------------------------------
### Type Definitions
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Complete interface definitions for all types used within the library, including field descriptions and usage examples.
```APIDOC
## Type Definitions
### Description
Provides detailed TypeScript definitions for all interfaces and types used in the library, ensuring type safety and clarity.
### Endpoint
`types.md`
### Parameters
#### Types
- **`Marker`** (object) - Represents a single data point on the map.
- **`id`** (string | number) - Unique identifier for the marker.
- **`coordinate`** (object) - Geographical coordinates of the marker.
- **`latitude`** (number) - Latitude value.
- **`longitude`** (number) - Longitude value.
- **`title`** (string) - Optional - Title displayed for the marker.
- **`description`** (string) - Optional - Description displayed for the marker.
- **`EdgePadding`** (object) - Defines the padding around the visible map region.
- **`top`** (number) - Padding at the top.
- **`right`** (number) - Padding at the right.
- **`bottom`** (number) - Padding at the bottom.
- **`left`** (number) - Padding at the left.
- **`Region`** (object) - Defines the visible map region.
- **`latitude`** (number) - Center latitude.
- **`longitude`** (number) - Center longitude.
- **`latitudeDelta`** (number) - Latitude span.
- **`longitudeDelta`** (number) - Longitude span.
### Type Usage Examples
```typescript
interface MyMarker extends Marker {
customData: any;
}
const myMarker: MyMarker = {
id: '1',
coordinate: { latitude: 37.78825, longitude: -122.4324 },
title: 'My Location',
customData: { /* ... */ }
};
const padding: EdgePadding = { top: 10, right: 10, bottom: 10, left: 10 };
```
```
--------------------------------
### Custom Render Function Example Usage
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/types.md
Shows how to implement a custom `renderCluster` function to display a custom Marker for each cluster. It uses cluster data to position and identify the marker.
```typescript
(
{/* Custom JSX */}
)} />
```
--------------------------------
### Accessing MapView Reference
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/api-reference/MapView.md
You can get a ref to the underlying MapView component to call its methods directly, such as `animateToRegion`.
```APIDOC
## Accessing MapView Reference
To use the component with a ref and access the underlying MapView methods:
```typescript
const mapRef = useRef();
const animateToRegion = () => {
mapRef.current.animateToRegion({
latitude: 42.5,
longitude: 15.2,
latitudeDelta: 7.5,
longitudeDelta: 7.5,
}, 2000);
};
return (
);
```
```
--------------------------------
### Custom Cluster Rendering
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/00_START_HERE.md
Provides an example of custom rendering for clusters using the `renderCluster` prop. This allows for completely custom marker components for clusters, displaying the point count.
```typescript
(
{cluster.properties.point_count}
)}
/>
```
--------------------------------
### Custom Navigation with onClusterPress
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/EVENTS_AND_CALLBACKS.md
Implement custom map navigation logic when a cluster is pressed. This example zooms to a single marker or fits all markers within a cluster to the view.
```typescript
const mapRef = useRef();
const handleClusterPress = (cluster, markers) => {
if (markers.length === 1) {
// Single marker: zoom to it
mapRef.current?.animateToRegion({
latitude: markers[0].geometry.coordinates[1],
longitude: markers[0].geometry.coordinates[0],
latitudeDelta: 0.01,
longitudeDelta: 0.01,
}, 500);
} else {
// Multiple markers: fit all
const coordinates = markers.map(m => ({
latitude: m.geometry.coordinates[1],
longitude: m.geometry.coordinates[0],
}));
mapRef.current?.fitToCoordinates(coordinates, {
edgePadding: { top: 100, left: 100, right: 100, bottom: 100 },
});
}
};
```
--------------------------------
### Example usage of markerToGeoJSONFeature
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/api-reference/helpers.md
Illustrates converting a React Marker element into a GeoJSON Feature, including its coordinate and other props.
```typescript
import { markerToGeoJSONFeature } from "react-native-map-clustering/lib/helpers";
import { Marker } from "react-native-maps";
const marker = ;
const feature = markerToGeoJSONFeature(marker, 0);
// Returns:
// {
// type: "Feature",
// geometry: { type: "Point", coordinates: [19.2, 52.5] },
// properties: { point_count: 0, index: 0, title: "Berlin" }
// }
```
--------------------------------
### Sync List with Map View
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/EVENTS_AND_CALLBACKS.md
Use onMarkersChange to synchronize an external list with the markers currently visible on the map. This example filters for individual markers and updates a FlatList.
```typescript
const [visibleItems, setVisibleItems] = useState([]);
const handleMarkersChange = (markers) => {
const items = markers
?.filter(m => !m.properties.cluster) // Only individual markers
.map(m => m.properties.id);
setVisibleItems(items);
};
return (
<>
{item} }
/>
>
);
```
--------------------------------
### Custom Cluster Rendering with Category Colors
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/ADVANCED_USAGE.md
Customize the appearance of clusters based on the properties of the markers they contain. This example sets different background colors for clusters based on a 'category' property (urgent, warning, default).
```typescript
const renderCluster = (cluster) => {
let backgroundColor = '#00B386'; // Default green
// Access custom properties from original markers
const properties = cluster.properties;
if (properties.category === 'urgent') {
backgroundColor = '#FF0000'; // Red for urgent
} else if (properties.category === 'warning') {
backgroundColor = '#FFA500'; // Orange for warning
}
return (
{cluster.properties.point_count}
);
};
```
--------------------------------
### Common SuperCluster Methods
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/EVENTS_AND_CALLBACKS.md
Demonstrates common methods available on the SuperCluster instance for querying cluster data, such as getting leaf features, clusters within a bounding box, and cluster expansion zoom levels.
```typescript
// Get all leaf (non-cluster) features for a cluster
const leaves = superClusterRef.current?.getLeaves(clusterId, maxZoom);
// Get clusters for a bounding box and zoom
const clusters = superClusterRef.current?.getClusters(bbox, zoom);
// Get cluster expansion zoom (zoom level where cluster expands)
const zoom = superClusterRef.current?.getClusterExpansionZoom(clusterId);
// Get cluster by ID
const cluster = superClusterRef.current?.getLeaves(clusterId, maxZoom);
```
--------------------------------
### Custom Cluster Styling with renderCluster
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/ADVANCED_USAGE.md
Completely customize cluster appearance using the renderCluster prop. This example shows basic custom rendering with a circular view displaying the point count.
```typescript
const renderCluster = (cluster) => {
const { point_count } = cluster.properties;
return (
{point_count}
);
};
```
--------------------------------
### Get Cluster Expansion Zoom with getClusterExpansionZoom
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/ADVANCED_USAGE.md
Gets the zoom level at which a cluster expands into its children using getClusterExpansionZoom. This can be used to animate the map to the appropriate zoom level.
```typescript
const handleClusterPress = (cluster) => {
const expansionZoom = superClusterRef.current?.getClusterExpansionZoom(cluster.id);
console.log(`Cluster expands at zoom ${expansionZoom}`);
// Animate to expansion zoom
mapRef.current?.animateToRegion({
latitude: cluster.geometry.coordinates[1],
longitude: cluster.geometry.coordinates[0],
latitudeDelta: 360 / Math.pow(2, expansionZoom),
longitudeDelta: 360 / Math.pow(2, expansionZoom),
}, 500);
};
```
--------------------------------
### Index Entry Point
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/MODULE_EXPORTS.md
The main entry point exports the ClusteredMapView component, wrapped in a memoization higher-order component.
```typescript
import * as MapView from "./lib/ClusteredMapView";
module.exports = MapView;
```
--------------------------------
### Event Callback Definitions
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Documentation for event callbacks, including parameter structures and execution order.
```Markdown
### onRegionChangeComplete Callback
- **Parameters**: `region` (object) - The new map region.
- **Description**: Called when the map's visible region has finished changing.
### onClusterPress Callback
- **Parameters**: `cluster` (object) - The cluster that was pressed, containing `points` and `centroid`.
- **Description**: Called when a cluster marker is pressed.
```
--------------------------------
### Event Callbacks
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Documentation for all callback functions, including their definitions, parameter structures, and execution order.
```APIDOC
## Events and Callbacks
### Description
Details the available callback functions that can be used to interact with map events, such as cluster presses and marker presses.
### Endpoint
`EVENTS_AND_CALLBACKS.md`
### Parameters
#### Callback Definitions
- **`onClusterPress(cluster)`**
- **`cluster`** (object) - Information about the pressed cluster.
- **`clusterId`** (string | number) - The ID of the cluster.
- **`pointCount`** (number) - The number of markers within the cluster.
- **`center`** (object) - The geographical center of the cluster.
- **`latitude`** (number)
- **`longitude`** (number)
- **`region`** (object) - The map region encompassing the cluster.
- **`latitude`** (number)
- **`longitude`** (number)
- **`latitudeDelta`** (number)
- **`longitudeDelta`** (number)
- **`onMarkerPress(marker)`**
- **`marker`** (object) - Information about the pressed marker.
- **`id`** (string | number) - The ID of the marker.
- **`coordinate`** (object) - The geographical coordinate of the marker.
- **`latitude`** (number)
- **`longitude`** (number)
### Callback Execution Order
Refer to `EVENTS_AND_CALLBACKS.md` for a diagram illustrating the callback execution order.
```
--------------------------------
### Basic MapView Usage with Markers
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/README.md
Demonstrates basic usage of the MapView component with initial region and multiple markers. Markers within the default clustering radius are automatically grouped.
```typescript
const INITIAL_REGION = {
latitude: 52.5,
longitude: 19.2,
latitudeDelta: 8.5,
longitudeDelta: 8.5,
};
export default function App() {
return (
);
}
```
--------------------------------
### State Management with Redux
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Illustrates state management patterns using Redux for dynamic map updates.
```JavaScript
// Redux action to update markers
const updateMarkers = (markers) => ({
type: 'UPDATE_MARKERS',
payload: markers
});
// Reducer to handle marker updates
const initialState = { markers: [] };
function mapReducer(state = initialState, action) {
if (action.type === 'UPDATE_MARKERS') {
return { ...state, markers: action.payload };
}
return state;
}
```
--------------------------------
### Troubleshooting: Marker Not Appearing
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Common troubleshooting steps when markers are not visible on the map.
```Markdown
### Troubleshooting:
- **Check Coordinates**: Ensure marker coordinates are valid and within the map's current viewport.
- **Clustering**: If clustering is enabled, verify `minPoints` and `maxZoom` settings. Try disabling clustering temporarily.
- **Z-Index**: Ensure markers are not obscured by other map elements or overlays.
- **Data Loading**: Confirm that marker data is loaded and passed correctly to the `MapView` component.
```
--------------------------------
### State Management with Context API
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Demonstrates state management using React's Context API for sharing map state.
```JavaScript
import React, { createContext, useState, useContext } from 'react';
const MapContext = createContext();
export const MapProvider = ({ children }) => {
const [markers, setMarkers] = useState([]);
return (
{children}
);
};
export const useMap = () => useContext(MapContext);
```
--------------------------------
### Region Change Callback
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/api-reference/MapView.md
Get notified when the map region changes and access the current region, details, and visible markers via the `onRegionChangeComplete` prop.
```APIDOC
## Region Change Callback
Access visible markers and current map region:
```typescript
const handleRegionChangeComplete = (region, details, markers) => {
console.log(`Map region: ${region.latitude}, ${region.longitude}`);
console.log(`Visible markers: ${markers.length}`);
};
{/* markers */}
```
```
--------------------------------
### Module Exports
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Documentation for the main module exports, including the entry point structure and a summary symbol table.
```APIDOC
## Module Exports
### Description
Details the main entry points and exports of the library, facilitating correct imports and usage.
### Endpoint
`MODULE_EXPORTS.md`
### Parameters
#### Main Exports
- **`MapView`** (component) - The primary component for displaying clustered markers.
- **`SuperCluster`** (class) - The underlying clustering engine, available for advanced usage.
### Import Path Guide
```javascript
import MapView from 'react-native-map-clustering';
// For advanced usage:
import SuperCluster from 'react-native-map-clustering/lib/SuperCluster';
```
### Summary Symbol Table
Provides a quick reference to all exported symbols. See `MODULE_EXPORTS.md` for the complete table.
```
--------------------------------
### Get Cluster Children with getLeaves
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/ADVANCED_USAGE.md
Retrieves all child markers (leaves) in a cluster using the getLeaves method. This is useful for accessing original marker properties within a cluster.
```typescript
const handleClusterPress = (cluster, markers) => {
const leaves = superClusterRef.current?.getLeaves(cluster.id, Infinity);
console.log(`Cluster ${cluster.id} has ${leaves?.length} leaves`);
// Access original marker properties
leaves?.forEach(leaf => {
console.log(leaf.properties.title); // Original marker prop
});
};
```
--------------------------------
### Animate Map to a Specific Region
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/README.md
Programmatically animate the map to a specified geographical region. This is useful for guiding user attention or navigating to points of interest. The animation duration can be controlled.
```typescript
const mapRef = useRef();
const zoomToRegion = () => {
mapRef.current?.animateToRegion({
latitude: 40.7128,
longitude: -74.0060,
latitudeDelta: 0.05,
longitudeDelta: 0.05,
}, 1000);
};
{/* markers */}
```
--------------------------------
### Importing Internal Utility Functions
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/MODULE_EXPORTS.md
Shows how to import specific internal utility functions from the helpers module for advanced usage.
```typescript
import { isMarker, calculateBBox, returnMapZoom, /* ... */ } from "react-native-map-clustering/lib/helpers";
```
--------------------------------
### Importing Type Definitions
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/MODULE_EXPORTS.md
Illustrates how to import TypeScript type definitions for MapClusteringProps and Cluster.
```typescript
import { MapClusteringProps, Cluster } from "react-native-map-clustering";
```
--------------------------------
### Custom Cluster Styling
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/00_START_HERE.md
Illustrates how to customize the appearance of clusters using props like `clusterColor`, `clusterTextColor`, and `clusterFontFamily`.
```typescript
```
--------------------------------
### Disable Clustering at High Zoom
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/EVENTS_AND_CALLBACKS.md
Conditionally disable clustering based on the zoom level detected in onRegionChangeComplete. This example shows how to adjust the clustering behavior based on the map's latitudeDelta.
```typescript
const handleRegionChangeComplete = (region) => {
const isZoomedIn = region.latitudeDelta < 0.5;
setClusteringEnabled(!isZoomedIn);
};
```
--------------------------------
### Show/Hide Markers Dynamically by Category
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/ADVANCED_USAGE.md
Control the visibility of markers based on their category using React state. This example filters a list of markers to only display those whose categories are included in the 'visibleCategories' state.
```typescript
import { useState } from "react";
const App = () => {
const [visibleCategories, setVisibleCategories] = useState(['food', 'lodging']);
const markers = [
{ id: 1, coordinate: { latitude: 52.4, longitude: 18.7 }, category: 'food' },
{ id: 2, coordinate: { latitude: 52.1, longitude: 18.4 }, category: 'lodging' },
{ id: 3, coordinate: { latitude: 52.6, longitude: 18.3 }, category: 'transport' },
];
const filteredMarkers = markers.filter(m => visibleCategories.includes(m.category));
return (
{filteredMarkers.map(marker => (
))}
);
};
```
--------------------------------
### Troubleshooting: Performance Issues with Many Markers
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/ADVANCED_USAGE.md
Address map lag with numerous markers by either increasing the clustering radius and minimum points for cluster formation or by implementing lazy loading of markers.
```typescript
// More aggressive clustering
// Or lazy-load markers
const [markers, setMarkers] = useState([]);
// Fetch markers only for current region
```
--------------------------------
### Memoize Marker Rendering for Performance
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/ADVANCED_USAGE.md
Optimize rendering performance for large marker sets by using `useMemo` to memoize the marker elements. This prevents unnecessary re-renders when the marker data hasn't changed.
```typescript
import { useMemo } from 'react';
const MyMapComponent = ({ markers }) => {
const memoizedMarkers = useMemo(() =>
markers.map(m => (
)),
[markers]
);
return (
{memoizedMarkers}
);
};
```
--------------------------------
### Filtering Markers by Custom Property in Cluster Press
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/ADVANCED_USAGE.md
Filter markers within a cluster based on their custom properties when the cluster is pressed. This example counts the number of 'food' and 'lodging' markers within a cluster.
```typescript
const handleClusterPress = (cluster, markers) => {
const restaurants = markers?.filter(m => m.properties.category === 'food') || [];
const hotels = markers?.filter(m => m.properties.category === 'lodging') || [];
Alert.alert(
`Cluster`,
`Restaurants: ${restaurants.length}\nHotels: ${hotels.length}`
);
};
```
--------------------------------
### Accessing Custom Marker Properties in Cluster Press
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/ADVANCED_USAGE.md
Process custom properties from markers within a cluster when the cluster is pressed. This example logs the unique categories and calculates the average rating of markers in the cluster.
```typescript
const handleClusterPress = (cluster, markers) => {
const categories = markers
?.map(m => m.properties.category)
.filter(c => c != null);
const ratings = markers
?.map(m => m.properties.rating)
.filter(r => r != null);
console.log(`Categories: ${[...new Set(categories)].join(', ')}`);
console.log(`Avg Rating: ${(ratings?.reduce((a, b) => a + b, 0) / ratings?.length).toFixed(1)}`);
};
```
--------------------------------
### Helper Functions for Map Clustering
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/QUICK_REFERENCE.md
Import and utilize various helper functions for tasks like checking marker types, calculating bounding boxes, and determining map zoom levels.
```typescript
import {
isMarker,
calculateBBox,
returnMapZoom,
markerToGeoJSONFeature,
generateSpiral,
returnMarkerStyle,
} from "react-native-map-clustering/lib/helpers";
// Check if element is clusterable
isMarker(child);
// Convert region to bounding box
calculateBBox(region); // → [minLng, minLat, maxLng, maxLat]
// Calculate zoom level
returnMapZoom(region, bbox, minZoom);
// Get marker dimensions
returnMarkerStyle(pointCount); // → { width, height, size, fontSize }
```
--------------------------------
### Map View Component Props
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Documentation for the MapView component props, including type specifications, default values, and return types.
```Markdown
## MapView Props
| Prop | Type | Default | Description |
|---|---|---|---|
| `clusteringEnabled` | `boolean` | `true` | Enables or disables marker clustering. |
| `clusterColor` | `string` | `#007AFF` | Color of the cluster marker. |
| `clusterTextColor` | `string` | `#FFFFFF` | Color of the text inside the cluster marker. |
| `maxZoom` | `number` | `null` | Maximum zoom level for clustering. |
| `minPoints` | `number` | `3` | Minimum number of points to form a cluster. |
| `renderCluster` | `(cluster: object) => React.ReactNode` | `null` | Custom component to render clusters. |
| `onRegionChangeComplete` | `(region: object) => void` | `null` | Callback when the map region changes. |
| `edgePadding` | `EdgePadding` | `{ top: 0, bottom: 0, left: 0, right: 0 }` | Padding around the map view. |
| `region` | `Region` | `null` | The current map region. |
```
--------------------------------
### Sync External Data with Visible Markers
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/EVENTS_AND_CALLBACKS.md
Synchronize external data sources with the markers currently visible on the map. The onMarkersChange callback can be used to get the IDs of visible individual markers and update external state accordingly.
```typescript
const handleMarkersChange = (markers) => {
const visibleIds = markers
?.filter(m => !m.properties.cluster)
.map(m => m.properties.id) || [];
updateHighlight(visibleIds); // Update external state
};
```
--------------------------------
### Dynamic Marker Clustering Radius Based on Zoom Level
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/ADVANCED_USAGE.md
Adjust the clustering radius dynamically based on the map's zoom level. This example uses the 'onRegionChangeComplete' event to calculate the zoom level and set an appropriate radius for clustering.
```typescript
const [radius, setRadius] = useState(Dimensions.get('window').width * 0.06);
const handleRegionChangeComplete = (region) => {
// Increase radius for zoomed-out views
const zoom = Math.log2(360 / region.longitudeDelta);
if (zoom < 8) {
setRadius(100); // Aggressive clustering
} else if (zoom < 12) {
setRadius(50); // Moderate clustering
} else {
setRadius(25); // Fine-grained clustering
}
};
{/* markers */}
```
--------------------------------
### Animate Map to Specific Region
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/README.md
Use the `animateToRegion` method on the map reference to smoothly transition the map view to a new geographical region. This is useful for guiding users to specific points of interest or updating the map's focus dynamically. Ensure the `mapRef` is correctly assigned to the MapView component.
```javascript
import React, { useRef } from "react";
import { Button } from "react-native";
import MapView from "react-native-map-clustering";
import { Marker } from "react-native-maps";
const INITIAL_REGION = {
latitude: 52.5,
longitude: 19.2,
latitudeDelta: 8.5,
longitudeDelta: 8.5,
};
const App = () => {
const mapRef = useRef();
const animateToRegion = () => {
let region = {
latitude: 42.5,
longitude: 15.2,
latitudeDelta: 7.5,
longitudeDelta: 7.5,
};
mapRef.current.animateToRegion(region, 2000);
};
return (
<>
>
);
};
export default App;
```
--------------------------------
### Document Dependency Graph
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/INDEX.md
Visualizes the relationships between different documentation files within the project. Helps understand the structure and interdependencies of the documentation.
```markdown
README.md (overview)
├── api-reference/MapView.md (main component)
│ ├── configuration.md (props details)
│ ├── types.md (TypeScript types)
│ └── ADVANCED_USAGE.md (custom rendering)
├── api-reference/ClusteredMarker.md (cluster rendering)
├── api-reference/helpers.md (utility functions)
├── EVENTS_AND_CALLBACKS.md (event system)
│ └── ADVANCED_USAGE.md (patterns)
├── MODULE_EXPORTS.md (symbol reference)
└── ADVANCED_USAGE.md (integration patterns)
```
--------------------------------
### Import MapView and Marker
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/QUICK_REFERENCE.md
Import the necessary components from react-native-map-clustering and react-native-maps.
```typescript
import MapView from "react-native-map-clustering";
import { Marker } from "react-native-maps";
```
--------------------------------
### TypeScript Definitions Export
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Demonstrates how TypeScript definitions are exported for better type safety.
```TypeScript
// types.ts
export interface MarkerProperties {
id: string;
coordinates: { latitude: number; longitude: number };
title?: string;
description?: string;
}
export interface MapState {
markers: MarkerProperties[];
region: Region;
}
// In another file:
import { MapState, MarkerProperties } from './types';
```
--------------------------------
### Types and Interfaces
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/INDEX.md
Defines the type structures used within the library, including props, cluster objects, and map-related interfaces.
```APIDOC
## Types and Interfaces
### MapClusteringProps
#### Description
Interface defining the properties accepted by the `MapView` component.
#### Document
`types.md`
### Cluster
#### Description
Type alias representing a cluster object.
#### Document
`types.md`
### Region
#### Description
Interface representing the map region, typically sourced from `react-native-maps`.
#### Document
`types.md`
### Marker
#### Description
Interface representing a marker object, typically sourced from `react-native-maps`.
#### Document
`types.md`
```
--------------------------------
### Performance Optimization: Reducing Re-renders
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Provides patterns for optimizing performance by minimizing unnecessary re-renders of map components.
```Markdown
### Performance Optimization Patterns:
1. **Memoization**: Use `React.memo` for custom marker components to prevent re-renders if props haven't changed.
2. **Stable References**: Ensure marker data arrays and objects have stable references, especially when passed down through props or context.
3. **Selective Updates**: Only update the map markers when the data has actually changed, rather than on every render cycle.
```
--------------------------------
### returnMarkerStyle()
Source: https://github.com/tomekvenits/react-native-map-clustering/blob/master/_autodocs/MODULE_EXPORTS.md
Returns CSS dimensions and font size for a cluster marker based on the number of points it contains. This helps in styling cluster markers dynamically.
```APIDOC
## returnMarkerStyle()
### Description
Returns CSS dimensions and font size for a cluster marker based on point count.
### Parameters
- **points** (number) - Number of markers in the cluster
### Returns
Object with pixel dimensions:
```typescript
{
width: number, // Outer container width
height: number, // Outer container height
size: number, // Inner circle diameter
fontSize: number // Text size in points
}
```
### Sizing Tiers
- 50+: 84×84, 64 inner, 20pt text
- 25-49: 78×78, 58 inner, 19pt text
- 15-24: 72×72, 54 inner, 18pt text
- 10-14: 66×66, 50 inner, 17pt text
- 8-9: 60×60, 46 inner, 17pt text
- 4-7: 54×54, 40 inner, 16pt text
- 2-3: 48×48, 36 inner, 15pt text
### Usage
```typescript
import { returnMarkerStyle } from "react-native-map-clustering/lib/helpers";
const style = returnMarkerStyle(25);
// Returns: { width: 78, height: 78, size: 58, fontSize: 19 }
```
```