在我的react native expo应用程序构建中使用google map API时面临的问题

y0u0uwnf  于 2023-11-21  发布在  React
关注(0)|答案(1)|浏览(145)

我正在做一个应用程序,我使用谷歌Map。Map应该显示用户的当前位置,通过纬度经度,当我们打开应用程序。但它不显示用户的当前位置。
下面是googleMapView组件的代码-

import { View, Text, StyleSheet } from 'react-native'
import React, { useContext, useEffect, useState } from 'react'
import MapView,{PROVIDER_GOOGLE} from "react-native-maps"
import { Dimensions } from 'react-native'
import { UserLocationContext } from '../../Context/UserLocationContext'

export default function GoogleMapView() {

    const [mapRegion,setmapRegion]=useState([])
    // const {location}=useContext(UserLocationContext)
    const {location,setLocation}=useContext(UserLocationContext)

    useEffect(()=>{
      if(location){
        console.log("User location", location)
        // console.log("1234")
        setmapRegion({
          latitude: location.coords.latitude,
          longitude: location.coords.longitude,
          latitudeDelta: 0.0522,
          longitudeDelta: 0.0421,
        })
      }
    },[])

  return (
    <View style={{marginTop:20}}>
      <Text style={styles.text}>Top Near By Places</Text>
      <View style={styles.container}>
        <MapView style={styles.map}
        showsUserLocation={true}
        provider={PROVIDER_GOOGLE}
        region={mapRegion}
        ></MapView>
    </View>
    </View>
  )
}

const styles=StyleSheet.create({
    map:{
        width:Dimensions.get("screen").width*0.93,
        height:Dimensions.get("screen").height*0.23,
        alignSelf:"center",
    },
    container:{
        borderRadius:20,
        overflow:"hidden"
    },
    text:{
      fontWeight:"bold",
      fontSize:16,
      marginBottom:10
    }
})

字符串
UserLocationContext代码-

import { createContext } from "react";

export const UserLocationContext=createContext(null)


GoogleMapView组件在home中呈现,该组件位于tabNavigation中,tabNavigation位于App.js中
App.js文件-

import { StyleSheet, Text, View, StatusBar ,SafeAreaView} from 'react-native';
import TabNavigation from './App/Navigations/TabNavigation';
import { NavigationContainer } from '@react-navigation/native';
import * as Location from 'expo-location';
import { useState,useEffect} from 'react';
import { UserLocationContext } from './App/Context/UserLocationContext';
import GoogleMapView from './App/Components/Home/GoogleMapView';

export default function App() {
  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);

  useEffect(() => {
    (async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }

      let location = await Location.getCurrentPositionAsync({});
      setLocation(location);
      // console.log(location)
    })();
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      <UserLocationContext.Provider 
      value={{location,setLocation}}>
      <NavigationContainer>
        <TabNavigation/>
      </NavigationContainer>
      </UserLocationContext.Provider>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
});


TabNavigation.js-

import { View, Text } from 'react-native'
import React from 'react'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'
import { NavigationContainer } from '@react-navigation/native';
import Home from '../Screen/Home';
import Profile from '../Screen/Profile';
import Search from '../Screen/Search';
import Favorite from '../Screen/Favorite';
import { Ionicons, Feather , MaterialIcons, FontAwesome} from '@expo/vector-icons';

const Tab=createBottomTabNavigator();

export default function TabNavigation() {
  return (
        <Tab.Navigator screenOptions={{
          tabBarActiveBackgroundColor:"#97a9b3",
          tabBarActiveTintColor:"white",
          headerShown:false,
        }}>
            <Tab.Screen name='Home' component={Home} options={{
              tabBarIcon:({color,size})=>(
                <Ionicons name="home" size={size} color={color} />
              )
            }}/>
            <Tab.Screen name='Search' component={Search} options={{
              tabBarIcon:({color,size})=>(
                <Feather name="search" size={size} color={color}/>
              )
            }}/>
            <Tab.Screen name='Favorite' component={Favorite} options={{
              tabBarIcon:({color,size})=>(
                <MaterialIcons name="favorite-border" size={size} color={color} />
              )
            }}/>
            <Tab.Screen name='Profile' component={Profile} options={{
              tabBarIcon:({color,size})=>(
                <FontAwesome name="user" size={size} color={color} />
              ),
            }}/>
        </Tab.Navigator>
  )
}


Home.js-

import { View, Text } from 'react-native'
import React from 'react'
import Header from '../Components/Home/Header'
import { SafeAreaView } from 'react-native-safe-area-context'
import GoogleMapView from '../Components/Home/GoogleMapView'

export default function Home() {
  return (
    <SafeAreaView style={{ paddingVertical:12, paddingHorizontal:15}}>
      <Header/>
      <GoogleMapView/>
    </SafeAreaView>
  )
}


我尝试在控制台中打印位置,以检查mapView中的useEffect是否正常工作。起初,当我打开应用程序时,它没有打印,但当我进行任何更改并保存文件时,它会在控制台中打印位置。但当我再次重新加载应用程序时,它不会打印,但在进行任何更改并保存后,它打印。所以可能是这个问题是因为useEffect。不知道这是什么问题。

chhqkbe1

chhqkbe11#

location更改时,useEffect不会重新运行。位置请求是异步的,可能需要一些时间来解决。将location添加到依赖项中,useEffect将在更改时重新运行。

useEffect(()=>{
  if(location){
    console.log("User location", location)
...
  }
}, [location])

字符串
请参阅useEffect了解更多信息。

相关问题