Skip to content

[Bug]: Invalid displacement location error React Native #2581

@BrunoArrojado

Description

@BrunoArrojado

Mapbox Implementation

Mapbox

Mapbox Version

main

Platform

Android

@rnmapbox/maps version

10.0.0-beta.65

Standalone component to reproduce

Created a Map component where I need the userLocation property enabled, nothing special there.

import React, { useEffect, useState } from 'react';
import {
  ImageBackground,
  StyleSheet,
  View,
  Dimensions,
  TouchableOpacity,
  Platform,
  ActivityIndicator,
  Alert
} from 'react-native';

import * as eva from '@eva-design/eva';
import {
  ApplicationProvider,
  Button,
  Icon,
  Layout,
  Text,
  TopNavigationAction
} from '@ui-kitten/components';

import { SafeAreaView } from 'react-native-safe-area-context';
// import { Button } from '../../components';
// import MapView, { Marker, UrlTile } from 'react-native-maps';
import Geolocation from '@react-native-community/geolocation';
import MapboxGL, { MarkerView, Logger, offlineManager, Point } from '@rnmapbox/maps';
import FormComponent from '../../components/Form';
import { useNavigation } from '@react-navigation/native';
import { useAPi } from '../../hooks/useApi';
// import { OfflineQueue } from '../components/OfflineQueue/Index';
import { FlexStyleProps } from '@ui-kitten/components/devsupport';
import Geocoder from 'react-native-geocoding';
import AwesomeAlert from 'react-native-awesome-alerts';

MapboxGL.setWellKnownTileServer('Mapbox');
MapboxGL.setAccessToken(
  'pk..Vmhb4mTtivGbAH8VGuyygw'
);

export type CoordinateTypes = {
  coords: {
    accuracy: number;
    altitude: number;
    altitudeAccuracy: number;
    heading: number;
    latitude: any;
    longitude: any;
    speed: number;
  };
  mocked: boolean;
  timestamp: number;
};

export const Map = ({ navigation, route }: { [key: string]: any }) => {




  const { screenType, languageDictionary } = route.params;
  const formData = screenType.find((e: any) => e?.step === 2);
  const backgroundImage = { uri: formData?.backgroundImage };
  // const [userLocation, setUserLocation] = useState<number[] | null>(
  //   null
  // );
  const [showAlertWindow, setshowAlert] = useState(false);
  const [alertMessage, setAlertMessage] = useState(
    { title: '', message: '' }
  );

  const [ocurrenceLocation, setOcurrenceLocation] = useState<number[] | null>(
    null
  );

  const showAlert = () => {
    setshowAlert(true);
  };

  const hideAlert = () => {
    setshowAlert(false);
  };

  let styleURL =
    'https://api.mapbox.com/styles/v1/examples/cjikt35x83t1z2rnxpdmjs7y7?access_token=pk..KISDQnxUxOX9XoYt-ryqrw' ||
    MapboxGL.StyleURL.Street;
  const [visible, setVisible] = React.useState(false);
  const [isGPSActive, setGPSActive] = React.useState(false);
  const [percentageMapIffline, setPercentageMapIffline] = React.useState(Number || null);

  if (!styleURL.includes(':/') && Platform.OS === 'android') {
    styleURL = `asset:/${styleURL}`;
  }

  // edit logging messages
  Logger.setLogCallback(log => {
    const { message } = log;
    // expected warnings - see https://github.com/mapbox/mapbox-gl-native/issues/15341#issuecomment-522889062
    if (
      message.match('Request failed due to a permanent error: Canceled') ||
      message.match('Request failed due to a permanent error: Socket Closed')
    ) {
      return true;
    }
    return false;
  });

  const { hasConnection } = useAPi();

  const WarningIcon = () => (
    <Icon fill="#FFFFFF" name="alert-triangle-outline" style={styles.icon} />
  );
  const onPressMap = async (e: Promise<any>) => {
    const response = await e;
  };

  const { favouritePlaceId, coordinates, placeName, customisedName } =
    route.params;

  const createPack = async () => {
    try {

      await MapboxGL.offlineManager.createPack({
        name: 'PortugalNorte',
        styleURL: "mapbox://styles/mapbox/streets-v12",
        minZoom: 15,
        maxZoom: 15,
        bounds: [[-9.052734, 39.580290], [-6.108398, 42.195969]]
      },
        (offlinePack, status) => { console.log(offlinePack, status); setPercentageMapIffline(status.percentage) },
        (offlinePack, err) => console.log(offlinePack, err),
      )
      console.log("Downloading")
    } catch (err) {
      const pack = await offlineManager.getPack(packName);
      if (pack) {
        const statusPack = await pack.status();
        console.log(statusPack.state)
        if (statusPack.state === 0) {
          console.log("apaga")
          pack.resume();
          MapboxGL.offlineManager.deletePack("Portugal");
        }
      }
      console.log(err)

    } finally {
      console.log("termimou")
    }
  }

  useEffect(() => {
    //createPack();
  }, []);
  const [packName, setPackName] = useState('Portugal');

  const handlePress = () => {
    console.log(ocurrenceLocation)
    if (ocurrenceLocation === null) {

      setAlertMessage(prevState => ({
        ...prevState,
        title: languageDictionary.translations[0].translation['missingField'],
        message: languageDictionary.translations[0].translation['errorMapLocalGPS']
      })); return showAlert()
    }
    navigation.navigate('Form', {
      screenType,
      languageDictionary,
      hasConnection,
      coordinates: ocurrenceLocation
    })
  }

  const renderAnnotations = () => {
    console.log(ocurrenceLocation)
    if (ocurrenceLocation) {
      return (
        <MapboxGL.PointAnnotation
          key="pointAnnotation"
          id="pointAnnotation"
          draggable={true}
          onDragEnd={(feature: any) => { setOcurrenceLocation(feature.geometry.coordinates) }}
          coordinate={ocurrenceLocation}>
          <View style={{
            height: 30,
            width: 30,
            backgroundColor: '#355724',
            borderRadius: 50,
            borderColor: 'red',
            borderWidth: 3
          }} />
        </MapboxGL.PointAnnotation>
      );
    }
  }

  return (

    <SafeAreaView style={styles.safeAreaView}>
      <View style={styles.container}>
        <AwesomeAlert
          show={showAlertWindow}
          showProgress={false}
          title={alertMessage.title}
          message={alertMessage.message}
          closeOnTouchOutside={true}
          closeOnHardwareBackPress={false}
          showCancelButton={false}
          showConfirmButton={true}
          confirmText="Ok"
          confirmButtonColor="#355724"
          onCancelPressed={() => {
            hideAlert();
          }}
          onConfirmPressed={() => {
            hideAlert();
          }}
        />
        <View
          style={{
            paddingLeft: '5%',
            height: 60,
            backgroundColor: 'rgba(53,87,36,0.5)',
            alignContent: 'center',
            justifyContent: 'center'
          }}>
          <Text>
            {(ocurrenceLocation == null) ?
              (
                <View>
                  <ActivityIndicator size="large" color="#355724" />
                  <Text>{languageDictionary.translations[0].translation['errorMapLocalGPS']}</Text>
                </View>
              )
              :
              (<Text>
                <Text> Latitude: {ocurrenceLocation[1]}{"\n"}</Text>
                <Text> Longitude:  {ocurrenceLocation[0]}</Text>
              </Text>)
            }
          </Text>
          {/* <Text>Downloading map: {percentageMapIffline.toFixed(2)} % Completed</Text> */}
        </View>
        {!hasConnection ? (
          <TouchableOpacity
            onPress={() => setVisible(true)}
            style={styles.topnav}>
            <Text style={styles.text} onPress={() => setVisible(true)}>
              <Icon
                fill="#FFFFFF"
                name="alert-triangle-outline"
                style={styles.icon}
              />
              {languageDictionary.translations[0].translation['youAreOffline']}
            </Text>
          </TouchableOpacity>
        ) : null}

        <View style={styles.mapContainer}>
          <MapboxGL.MapView
            style={styles.map}
            styleURL={MapboxGL.StyleURL.Street}
            logoEnabled={true}
            localizeLabels={true}
            onPress={(feature) => { console.log('Coords:', JSON.stringify(feature.geometry)); setOcurrenceLocation(feature.geometry.coordinates) }}
          >
            <MapboxGL.UserLocation
              visible={true}
              // onUpdate={onUserLocationUpdate}
              showsUserHeadingIndicator={Platform.OS === 'ios'}
            />
            <MapboxGL.Camera
              zoomLevel={10}
              animationMode={'flyTo'}
              animationDuration={2000}
              // centerCoordinate={[-7.8537, 39.5572]}
              followUserLocation={true}
            />
            {(ocurrenceLocation) &&
              renderAnnotations()}

          </MapboxGL.MapView>
          <View style={styles.bottom}>
            <Button
              style={styles.buttonSubmitContainer}
              onPress={handlePress}>
              {languageDictionary.translations[0].translation['continue']}
            </Button>
            <View style={{ position: 'absolute', flex: 1 }}></View>
          </View>
        </View>
      </View>
    </SafeAreaView >
  );
};
// Styles
const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#fff' },
  mapContainer: {
    flex: 1,
    alignItems: 'center'
  },
  map: {
    ...StyleSheet.absoluteFillObject
  },
  safeAreaView: {
    flex: 1
  },
  buttonSubmitContainer: {
    backgroundColor: '#355724',
    borderRadius: 6,
    height: 45,
    width: 200,
    alignItems: 'center'
  },
  bottom: {
    flex: 1,
    justifyContent: 'flex-end',
    marginBottom: 36
  },
  topnav: {
    backgroundColor: 'rgba(136, 8, 8, 0.5)',
    color: '#FFFFFF',
    justifyContent: 'center',
    width: '100%',
    height: 35,
    zIndex: 999
  },
  backdrop: {
    backgroundColor: 'rgba(0, 0, 0, 0.5)'
  },
  buttonTiny: {
    margin: 2
  },
  icon: {
    width: 20,
    height: 20,
    justifyContent: 'center'
  },
  text: {
    color: 'white',
    fontSize: 16,
    lineHeight: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    justifyContent: 'center'
  }
});


Observed behavior and steps to reproduce

Observed behavior and steps to reproduce
I was running an app using mapbox for some time, and since this weekend, after reinstalling npm the app after requesting the the location permission started to crash.

If I comment the mapbox code, it will work, can you please help?

image

Expected behavior

No errors

Notes / preliminary analysis

No response

Additional links and references

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions