Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In ios when i click on cluster first it zoom then navigate to that cordinates #3760

Open
12varun12 opened this issue Jan 30, 2025 · 1 comment

Comments

@12varun12
Copy link

Environment

  • Dev OS: [e.g. OSX 11.0.1, Win10]
  • @rnmapbox/maps version:10.1.33
  • React Native version: 0.76.6

Steps to reproduce

when i click on map icon then zoomin the map and zoom out at same time but our functionality is when user click on icon then one bottom sheet is open

import React, { useContext, useState, useEffect, useRef, useMemo, memo } from 'react';
import {
    StyleSheet,
    ActivityIndicator,
    View,
    PermissionsAndroid,
    Platform,
    Text,
    Linking,
    Button,
    AppState,
} from 'react-native';
import MapboxGL from '@rnmapbox/maps';

import { AuthContext } from '../../context/AuthContext';
import { LocationContext } from '../../context/LocationContext';
import ListView from './ListView';
import { CLUB_DETAILS_MAP } from '../../service/EndPoint';
import { fetcher } from '../../service/fetcher';
import MapSearchResults from '../search/MaPSearchResults';
import UserLocationButton from '../buttons/UserLocationButton';
import ClubDetailsPopup from './ClubDetailsPopup';
import { GlobalContext } from '../../context/contextApi';
import MapCluster from './MapCluster';
import { NativeEventEmitter, NativeModules } from 'react-native';
import ScreenResizeButton from '../buttons/ScreenResizeButton';
import { getRecommendedClubs } from '../../screens/requests/Utils';
import constants from '../../utils/constants/constants';
const CleverTap = require('clevertap-react-native');
import routes from '../../config/routes';
import { useNavigation } from '@react-navigation/native';

function ClubMap({
    clubs,
    activeView,
    filter,
    setActiveView,
    locations,
    searchingState,
    searchInputState,
    clubDetailDrawerOpen,
    setClubDetailDrawerOpen,
    selectedClub,
    setSelectedClub,
    setMapBoundaries,
    searchedClubList,
    screenSize,
    moreDetailListView,
    setMoreDetailListView,
    isComeFromMap,
    setIsComeFromMap,
    setShowSearch,
    zoomLevel,
}) {
    const { user } = useContext(AuthContext);
    const navigation = useNavigation();
    const { state, actions } = useContext(GlobalContext);
    const { userLocation, getLocation } = useContext(LocationContext);
    const [locationPermissionGranted, setLocationPermissionGranted] = useState(false);
    const [searching, setSearching] = searchingState;
    const [centerCoordinates, setCenterCoordinates] = useState([
        state?.mapCurrentState?.lng || 37.0902,
        state?.mapCurrentState?.lat || 95.7129,
    ]);
    const camera = useRef(null);
    const map = useRef(null);
    const [searchType, setSearchType] = useState('');
    const [ownClub, setOwnClub] = useState();
    const [requestedClub, setRequestedClub] = useState({});
    const [recommendedClubs, setRecommendedClubs] = useState([]);
    const [showRecommendationPopup, setShowRecommendationPopup] = useState(false);

    let appStateEmitter;
    useEffect(() => {
        if (Platform.OS === 'android') appStateEmitter = new NativeEventEmitter();
    }, []);

    const newClub = useMemo(() => {
        return clubs?.map((item) => {
            if (item.geometry.coordinates[0] === null && item.geometry.coordinates[1] === null) {
                return {
                    ...item,
                    geometry: {
                        type: 'Point',
                        coordinates: [0, 0],
                    },
                };
            } else {
                return item;
            }
        });
    }, [clubs]);

    // This function is used to change the region nad location on tap on any searched location
    async function animateMapToBoundaries(params) {
        setActiveView('MAP');
        setSearching(false);
        const { location } = params;
        changeRegion(location?.lat, location?.lng, false);
    }

    const checkAndroidPerms = () => {
        PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION)
            .then((permission) => {
                if (!permission) {
                    getAndroidPermission();
                } else {
                    setLocationPermissionGranted(permission === 'denied' ? false : permission);
                }
            })
            .catch((err) => console.log('hello123', err));
    };
    const getAndroidPermission = () => {
        PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION)
            .then((permission) => {
                if (locationPermissionGranted !== permission) {
                    setLocationPermissionGranted(permission === 'denied' ? false : permission);
                }
            })
            .catch((err) => console.log('hello456', err));
    };

    const handleClubPress = ({ id, properties: { color } }) => {
        CleverTap.recordEvent(constants.CLEVERTAP.EVENTS.GOLF_CLUBS, { clubId: id });
        const body = {
            userId: user?.id,
            clubId: Number(id),
            clubColor: color,
        };
        fetcher({
            endpoint: CLUB_DETAILS_MAP,
            method: 'POST',
            body,
        })
            .then((data) => {
                const { lat, lng } = data?.clubs;
                if (lat && lng) {
                    setActiveView('MAP');
                    setSearching(false);
                    setSelectedClub(data);
                    actions.setMapCurrentClub(data); // Set current club on which user clicked and it is used to open club details when user come from another tab
                }
            })
            .catch(console.log);
    };

    // This function called when we change the region on map
    const handleRegionChange = async (data) => {
        try {
            //If the coordinates are same then do not change the map state
            if (
                state?.mapCurrentState?.lat === data?.geometry?.coordinates[1] &&
                state?.mapCurrentState?.lng === data?.geometry?.coordinates[0]
            ) {
                return;
            }
            actions?.setMapCurrentState({
                lat: data?.geometry?.coordinates[1],
                lng: data?.geometry?.coordinates[0],
            });

            // actions?.setZoomLevelState(data?.properties?.zoomLevel);
            actions.setMapCurrentClub(); // Set current club on which user clicked and it is used to open club details when user come from another tab
            setMapBoundaries(data?.properties?.visibleBounds);
        } catch (error) {
            console.log('handleRegionChange --->', error);
        }
    };

    // This function is used for move the map to the searched or current location
    const changeRegion = async (latitude, longitude, isZoomNeeded) => {
        camera.current?.moveTo([longitude, latitude]);
        setCenterCoordinates([Number(longitude), Number(latitude)]);
        if (isZoomNeeded) {
            setTimeout(() => {
                camera.current?.zoomTo(10, 100);
            }, 300);
        }
    };

    //this function is call when we click on any club marker
    const onPressClubMarker = (club) => {
        setIsComeFromMap(true);
        actions?.setClubDetails(club);
        handleClubPress(club);
    };

    //this function is call when we click on any club in list view
    const onPressClub = (club) => {
        setIsComeFromMap(false);
        setMoreDetailListView(true);
        actions?.setClubDetails(club);
        handleClubPress(club);
    };

    const onMarkerPressed = async (item) => {
        if (item.features[0].properties.cluster) {
            const zoom = await map.current?.getZoom();
            camera.current?.moveTo(item.features[0].geometry.coordinates);
            setCenterCoordinates(item.features[0].geometry.coordinates);
            actions?.setMapCurrentState(item.features[0]?.geometry?.location);
            camera.current?.zoomTo(zoom + 2, 0);
        } else {
            onPressClubMarker(item.features[0]);
            actions.setMapCurrentClub(item.features[0]); // Set current club on which user clicked and it is used to open club details when user come from another tab
        }
    };

    useEffect(() => {
        let temporaryClub = [];
        user?.clubs?.map((club) => {
            temporaryClub.push(club?.club_id);
        });
        setOwnClub(temporaryClub);
    }, [user]);

    // this useEffect is used to set current user location
    useEffect(() => {
        if (userLocation != null) {
            changeRegion(
                state?.mapCurrentState?.lat || userLocation?.latitude,
                state?.mapCurrentState?.lng || userLocation?.longitude,
            );
            // For open club details bottomSheet
            setTimeout(() => {
                setSelectedClub(state?.mapCurrentClub);
            }, 2000);
        }
    }, [userLocation]);

    useEffect(() => {
        if (Platform.OS === 'ios') {
            setLocationPermissionGranted(true);
        } else {
            checkAndroidPerms();
            const subscription = appStateEmitter.addListener('ActivityStateChange', (e) => {
                if (e.event === 'active') {
                    checkAndroidPerms();
                }
            });

            return () => {
                subscription.remove();
            };
        }
    }, []);

    useEffect(() => {
        if (locationPermissionGranted && Platform.OS === 'android') {
            getLocation();
        }
    }, [locationPermissionGranted]);

    useEffect(() => {
        if (locationPermissionGranted && !userLocation && Platform.OS === 'ios') {
            getLocation();
        }
    }, [locationPermissionGranted, userLocation]);
    
    const handleCurrentLocation = () => {
        actions?.setMapCurrentState({
            lat: userLocation?.latitude,
            lng: userLocation?.longitude,
        });
        changeRegion(userLocation?.latitude, userLocation?.longitude, true);
        // }
    };

    useEffect(() => {
        if (requestedClub?.id) {
            const getClub = async () => {
                const res = await getRecommendedClubs({ userId: user?.id, clubId: requestedClub?.id });
                if (res?.status === 1) {
                    if (res?.data?.length) {
                        setRecommendedClubs(res?.data);
                        navigation.navigate(routes.RECOMMENDED_CLUB, {
                            recommendedClubs: res?.data,
                            requestedClub,
                        });
                    }
                }
            };

            getClub();
        }
    }, [requestedClub]);

    if (userLocation && newClub && locationPermissionGranted && locationPermissionGranted !== 'never_ask_again') {
        return (
            <View style={{ flex: 1 }}>
                <MapboxGL.MapView
                    style={{ flex: 1 }}
                    ref={map}
                    onRegionDidChange={(e) => {
                        handleRegionChange(e);
                    }}
                    onDidFinishLoadingMap={() => {
                        console.log("onDidFinishLoadingMap")
                    }}
                    attributionEnabled={false}
                    compassEnabled={false}
                    scaleBarEnabled={false}
                    rotateEnabled={false}
                    logoEnabled={false}
                    pitchEnabled={false}>
                    <MapboxGL.UserLocation
                        // renderMode="native"
                        visible={true}
                    />
                    <MapboxGL.Camera
                        ref={camera}
                        minZoomLevel={4}
                        maxZoomLevel={13}
                        animationDuration={2000}
                        animationMode="moveTo"
                        zoomLevel={
                            zoomLevel
                                ? zoomLevel
                                : searchType === 'club'
                                ? 12
                                : searchType === 'location'
                                ? 6
                                : state?.firstTimeInMap
                                ? 12
                                : 12
                        }
                        centerCoordinate={centerCoordinates}
                    />
                    <MapCluster clubs={newClub} onItemPress={onMarkerPressed} selectedClub={selectedClub} />
                </MapboxGL.MapView>
                <UserLocationButton setUserRegion={handleCurrentLocation} />
                <ScreenResizeButton screenSize={screenSize} setShowSearch={setShowSearch} />
                {activeView === 'LIST' && (
                    <ListView
                        listItems={state?.boundariesChangeClub}
                        user={user}
                        myClubs={newClub}
                        onPressClub={onPressClub}
                        setMoreDetailListView={setMoreDetailListView}
                        moreDetailListView={moreDetailListView}
                    />
                )}
                <MapSearchResults
                    searchedClubList={searchedClubList}
                    locations={locations}
                    searchInputState={searchInputState}
                    searchingState={searchingState}
                    setSelectedClub={setSelectedClub}
                    setMapLocation={animateMapToBoundaries}
                    setActiveView={setActiveView}
                    setSearching={setSearching}
                    changeRegion={changeRegion}
                    setCenterCoordinates={setCenterCoordinates}
                    setSearchType={setSearchType}
                />
                <ClubDetailsPopup
                    club={selectedClub}
                    user={user}
                    filter={filter}
                    myClubs={newClub}
                    setSelectedClub={setSelectedClub}
                    clubDetailDrawerOpen={clubDetailDrawerOpen}
                    setClubDetailDrawerOpen={setClubDetailDrawerOpen}
                    ownClub={ownClub}
                    setMoreDetailListView={setMoreDetailListView}
                    moreDetailListView={moreDetailListView}
                    setActiveView={setActiveView}
                    isComeFromMap={isComeFromMap}
                    setIsComeFromMap={setIsComeFromMap}
                    setRequestedClub={setRequestedClub}
                    recommendedClubs={recommendedClubs}
                    requestedClub={requestedClub}
                    showRecommendationPopup={showRecommendationPopup}
                    setShowRecommendationPopup={setShowRecommendationPopup}
                />
            </View>
        );
    }

    if (!locationPermissionGranted || locationPermissionGranted === 'never_ask_again') {
        return (
            <View style={styles.noLocPerms}>
                <View
                    style={{
                        flex: 1,
                        alignItems: 'center',
                        justifyContent: 'center',
                    }}>
                    <Text style={{ padding: 40, textAlign: 'center' }}>
                        You must enable location permissions in your phone's settings to use the Clubs map.
                    </Text>
                    <Button
                        title="Open Settings"
                        onPress={() => {
                            Linking.openSettings().then((v) => console.log({ LINKINNGGGGGGGGG: v }));
                        }}
                    />
                </View>
            </View>
        );
    }

    return (
        <View style={styles.loader}>
            <ActivityIndicator size="large" />
        </View>
    );
}

export default memo(ClubMap);

const styles = StyleSheet.create({
    map: {
        flex: 1,
    },
    loader: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: 'gray',
    },
    noLocPerms: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: 'white',
        borderRadius: 15,
        zIndex: 0,
    },
    marker: {
        shadowColor: 'black',
        shadowOffset: {
            width: 2,
            height: 0,
        },
        shadowOpacity: 0.5,
        shadowRadius: 2,
    },
    markerParent: {
        height: 40,
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        alignContent: 'flex-end',
    },
    markerText: {
        maxWidth: 120,
        fontWeight: 'bold',
    },
});

@12varun12 12varun12 changed the title on click on cluster map is zoom and and again back to same zoom level In ios when i click on cluster first it zoom then navigate to that cordinates Jan 30, 2025
@12varun12
Copy link
Author

when I click on cluster first of all zoom the map then navigate to particular coordinates but it is working fine in Android and also Mapbox logo, info icon and compass logo is visible in ios in Android it is not visible which is correct i have to hide from ios and one more issue is when i click on marker which is very close to cluster then according to my login bottom sheet is open but that marker behave like a cluster and provide the zoom an not open the bottom sheet but in case i click on isolated marker bottom sheet is open and working fine.
please provide me the solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant