在我的应用程序构建中使用 google 地图 api 和 React Native expo 时遇到问题

问题描述 投票:0回答:1

我正在制作一个使用谷歌地图的应用程序。当我们打开应用程序时,地图应通过纬度经度显示用户当前的位置。但它没有显示用户的当前位置。

这是 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 组件在 tabNavigation 内的 home 内呈现,而 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 造成的。不知道这有什么问题。

react-native react-hooks google-maps-api-3 react-context
1个回答
0
投票

useEffect

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

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

请参阅 useEffect 了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.