1

<MapboxGL.UserLocation> 中的 UserIndicator,在 IOS 上可以正常工作和显示,但对于 android,它取决于,它有时工作,有时不工作,而且我也意识到,当 UserIndicator 没有时,我的 CameraRef.current.setCamera() 未定义不显示。

我尝试尽我所能请求位置权限,如下所示:

反应原生:

    PermissionsAndroid.requestMultiple(
  [PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION],
  {
    title: 'Give Location Permission',
    message: 'App needs location permission to find your position.'
  }
).then((res) => console.log(res))

MapboxGL:

if (Platform.OS == "android") {
    var temp = await MapboxGL.requestAndroidLocationPermissions()
}

世博会:

let { status } = await Location.requestPermissionsAsync();

所有这些请求权限都可以正常工作,并且输出“已授予”或已授予:true

这是我的地图组件:

var Map = ({ navigation }) => {
  const MapRef = React.useRef(null)
  const CameraRef = React.useRef(null)
  const LocationRef = React.useRef(null)
  const { user, setUser } = React.useContext(UserContext)
  const [data, setDATA] = React.useState([null])
  const [reload, setReload] = React.useState(false)
  const {location, setLocation} = React.useContext(LocationContext)
  console.log(location)
  var test = null;
  React.useEffect(() => {
    MapboxGL.setTelemetryEnabled(false);
    MapboxGL.locationManager.start();
    return () => {
      MapboxGL.locationManager.stop();
    }
    // console.log(LocationRef.current)
  }, [])
  function handleClick() {
    CameraRef.current.setCamera({
      centerCoordinate: [location.coords.longitude, location.coords.latitude],
      zoomLevel: 11,
      animationDuration: 200,
    })
  }
  function CenterCamera() {
    if (CameraRef.current) {
      CameraRef.current.setCamera({
        centerCoordinate: [location.coords.longitude, location.coords.latitude],
        zoomLevel: 11,
        animationDuration: 2000,
      })
    }
  }
  function goTo(latitude, longitude) {
    CameraRef.current.setCamera({
      centerCoordinate: [longitude, latitude],
      zoomLevel: 13,
      animationDuration: 100,
    })
  }
  function DisplayPings(data) {
    if (data.data.length > 0) {
      if (data.data[0].type_id == null) {
        data.data[0].type_id = 1;
      }
      const val = searchInJson(data.data[0].type_id)
      const features = setFeatures(val, data.data[0])
      return (
        <View key={data.data[0].id_activity_data}>
          <MapboxGL.Images
            images={{
              FootBall: json[0].url,
            }}
          />
          <MapboxGL.ShapeSource hitbox={{ width: 20, height: 20 }} onPress={() => goTo(data.data[0].latitude, data.data[0].longitude)} id={(data.data[0].id_activity_data).toString()} shape={features}>
            <MapboxGL.SymbolLayer id={(data.data[0].id_activity_data).toString()} style={{ iconImage: ['get', 'icon'] }} />
          </MapboxGL.ShapeSource>
        </View>
      );
    }
  }
  if (location && location.city != null && data.data) {
    return (
      <View style={styles.page}>
        <MapboxGL.MapView onPress={() => console.log("test")} ref={(ref) => {
        }
        } style={styles.map} compassEnabled={false} zoomEnabled={true} >
          <MapboxGL.UserLocation />
          <MapboxGL.Camera ref={(ref) => {
            CameraRef.current = ref
            CenterCamera()
          }} />
          {data.data.map((data) => DisplayPings(data))}
        </MapboxGL.MapView>
        <ComponentsOnmap></ComponentsOnmap>
        <TouchableOpacity style={styles.rondLocation} onPress={handleClick}>
          <FontAwesome5 name="location-arrow" size={24} color="#434040" />
        </TouchableOpacity>
        <BottomSheet city={location.city} data = {data} setReload = {setReload} navigation={navigation}></BottomSheet>
      </View>)
  }
  else
    return (
      <View style={styles.page}>
        <MapboxGL.MapView ref={MapRef} compassEnabled={false}  style={styles.map} zoomEnabled={true} >
          <MapboxGL.UserLocation ref={LocationRef} />
        </MapboxGL.MapView>
        <ComponentsOnmap></ComponentsOnmap>
        <BottomSheet city="No location" navigation={navigation}></BottomSheet>
      </View>
    )
}

export default Map 

我的条件 location && location.city != null 工作正常,我试过没有它,但问题还是一样

我的位置上下文:

import React, { Component, createContext, useState, useContext } from "react";
import { Platform, PermissionsAndroid } from "react-native"
import * as Location from 'expo-location';
import MapboxGL from "@react-native-mapbox-gl/maps";
import { GetLocation } from "../API/GetLocation"
export const LocationContext = createContext();

MapboxGL.setAccessToken("Je l'ai caché bande de petit malin");

export default LocationProvider = ({ children }) => {
  const [location, setLocation] = useState({ coords: [], city: null, permission: false })
  const [city, SetCity] = React.useState(null)
  const [coords, setCoords] = React.useState([])
  React.useEffect(() => {
    PermissionsAndroid.requestMultiple(
      [PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION],
      {
        title: 'Give Location Permission',
        message: 'App needs location permission to find your position.'
      }
    ).then((res) => console.log(res))
    GetLocation.then((res) => {
      setLocation(res)
    })
  }, [])

  return (
    <LocationContext.Provider value={{ location, setLocation, city, SetCity, coords, setCoords }}>
      {children}
    </LocationContext.Provider>
  )
}

我的 GetLocation 承诺

import { useContext } from "react"
import { Platform } from "react-native"
import * as Location from 'expo-location';
import MapboxGL from "@react-native-mapbox-gl/maps";

export const GetLocation = new Promise(async (resolve, reject) => {
    if (Platform.OS == "android") {
        var temp = await MapboxGL.requestAndroidLocationPermissions()
    }
    let { status } = await Location.requestPermissionsAsync();
    if (status == "granted")
        Location.getCurrentPositionAsync().then((location) => {
            console.log(location)
            console.log("ca marche ap")
            let longitude = location.coords.longitude
            let latitude = location.coords.latitude
            return ({ latitude, longitude })
        }).then(async (coords) => Location.reverseGeocodeAsync(coords).then(async (adress) => {
            resolve({ coords: coords, city: adress[0].city, granted: true })
        })).catch((error) => console.log(reject(error)));
})

     
4

0 回答 0