Search code examples
react-nativereact-native-map-clustering

How to cluster all Markers except one


i am using react-native-map-clustering for clustering Markers on the google map. All of Markers are dynamic except one, which indicates my location. When i zoom out map clusters all Markers. But i want something like this enter image description here Here is my implementation:

<MapView
            layoutAnimationConf={LayoutAnimation.Presets.easeInEaseOut}
            animationEnabled={true}
            ref={mapRef}
            style={styles.map}
            provider={PROVIDER_GOOGLE}
            initialRegion={currentRegion}
            // region={currentRegion}
            clusteringEnabled={true}
            radius={70}
            customMapStyle={mapConfig}>
            <Marker coordinate={currentRegion} title={'my location'}>
                <Image
                    source={images.currentLocation}
                    style={{
                        height: 20,
                        width: 20,
                    }}
                />
            </Marker>
            {branchMarkers()}
        </MapView>

Solution

  • You can set the cluster prop on the Marker to false like so:

    <Marker
      coordinate={coordinate}
      cluster={false}
      ...
    />
      <Image ... />
    </Marker>
    

    This will keep this one Marker permanently declustered and visible on the map at all zoom levels, not affecting other clusters. Internally, for each Marker which is a child of the MapView, a check if that Marker should be included in a cluster is done in a helper function that checks if this prop has been overridden:

    export const isMarker = (child) =>
      child &&
      child.props &&
      child.props.coordinate &&
      child.props.cluster !== false;
    

    Note for TypeScript users:

    react-native-map-clustering does not export a Marker component with a defined cluster prop. Applying cluster prop to a Marker imported from react-native-maps will trigger a ts compiler error, so you'd need to define your own Marker type or ignore this ts error.