Load markers on map by bounds instead of all

This commit is contained in:
Maarten 2024-08-13 11:37:40 +02:00
parent f3213ae588
commit 37ad9d5a2f

View file

@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { Image, SafeAreaView, ScrollView, StatusBar, StyleSheet, Switch, View, Dimensions } from 'react-native';
import Mapbox, { Callout, Camera, MapView, PointAnnotation } from "@rnmapbox/maps";
import { useSelector } from 'react-redux';
@ -17,42 +17,57 @@ import { Request } from '@/src/services/request';
export default function MapScreen() {
const colorScheme = useColorScheme() ?? 'light';
const isFocused = useIsFocused();
const session = useSelector((state: any) => state.data.session);
const session = useSelector( (state: any) => state.data.session );
const { t } = useTranslation();
const mapRef = useRef<MapView>( null );
const [ types, setTypes ] = useState<any>( [] );
const [ typesSet, setTypesSet ] = useState( false );
const [ coordinates, setCoordinates ] = useState<any>( [] );
const [ markers, setMarkers ] = useState<any>( [] );
// Load session
useEffect( () => {
setCoordinates([session.coordinates.longitude, session.coordinates.latitude]);
}, [session, isFocused]);
setCoordinates( [ session.coordinates.longitude, session.coordinates.latitude ] );
}, [ session, isFocused ] );
// Load markers and types
// Setup mapbox
useEffect( () => {
Mapbox.setTelemetryEnabled( false );
Request.get( 'locations' ).then( (response) => {
const { locations, types } = response;
// Set types
const typesList: any[] = [];
types.forEach( (type: any) => {
typesList.push( {
name: type.name,
image: type.image,
isEnabled: false,
type: type.config_name,
} );
} )
setTypes( typesList );
// Set markers
setMarkers( locations );
} )
}, [] );
// Load markers and types
const loadMarkers = () => {
mapRef.current?.getVisibleBounds().then( (bounds) => {
Request
.post( 'locations', {
topLeft: bounds[ 0 ],
bottomRight: bounds[ 1 ],
} )
.then( (response) => {
const { locations, types } = response;
// Set types
if (!typesSet) {
const typesList: any[] = [];
types.forEach( (type: any) => {
typesList.push( {
name: type.name,
image: type.image,
isEnabled: false,
type: type.config_name,
} );
} )
setTypes( typesList );
setTypesSet( true );
}
// Set markers
setMarkers( locations );
} )
} );
}
// Enable/disable type
const toggleSwitch = (index: any) => {
const newData = types.map( (item: any, key: any) =>
@ -96,10 +111,12 @@ export default function MapScreen() {
<ThemedView style={styles.mapContainer}>
<MapView
ref={mapRef}
style={styles.map}
logoEnabled={false}
scaleBarEnabled={false}
attributionEnabled={false}
onMapIdle={loadMarkers}
>
<Camera
centerCoordinate={coordinates.length == 2 ? coordinates : undefined}