简体   繁体   中英

using React-Native with expo map location screen is problem

I want to show my location in the screen but the screens shows ocean. My location do not appear not immediately in first screen. I have to press locationButton to see my location. Is there any way to show my location?? ppls help me.

I am using react native/ javascript by expo

this is the screen that shows in the first place

this is the screen I WANT

This is my code

import React, { useState, useEffect, useLayoutEffect } from 'react';

import styled from 'styled-components/native';

import { Button } from '../components/index.js';
import { Text, View, StyleSheet, Dimensions, SafeAreaView, TouchableOpacity} from "react-native";
import MapView, { PROVIDER_GOOGLE } from 'react-native-maps';
import { Location, Permissions } from 'expo';
import { AntDesign, MaterialCommunityIcons } from '@expo/vector-icons';
import Icon from 'react-native-vector-icons/Ionicons';
import {Stopwatch} from 'react-native-stopwatch-timer';
import { createStackNavigator } from "@react-navigation/stack";



const height = Dimensions.get('window').height-350
const Stack = createStackNavigator();

const ChannelCreation = ({ navigation }) => {
    const [currentLatitude, setCurrentLatitude] = useState('unknown');
    const [currentLongitude, setCurrentLongitude] = useState('unknown');
    const [watchID, setWatchID] = useState('');

    const [initialRegion, setInitialRegion] = useState({
        latitude: 37.4214418,
        longitude: 126.9891955,
        latitudeDelta: 0.008,
        longitudeDelta: 0.008
    })
    
    const [mapWidth, setMapWidth] = useState('99%');
    const [location, setLocation] = useState(null);
    const [errorMsg, setErrorMsg] = useState(null);
    
    const updateMapStyle = () => {
        setMapWidth('100%')
    }

    const [isStopwatchStart, setIsStopwatchStart] = useState(false);
    const [resetStopwatch, setResetStopwatch] = useState(false);
    
    useEffect(() => {
        (async () => {
            let {status} = await Location.requestForegroundPermissionsAsync();
            if (status !== 'granted'){
                setErrorMsg("Permission to access location was denied");
                return;
            }

            navigator.geolocation.getCurrentPosition(
                position => {
                    currentLatitude = JSON.stringify(position.coords.latitude);
                    currentLongitude = JSON.stringify(position.coords.longitude);
                    // currentLatitude = currentLatitude;
                    // currentLongitude = currentLongitude;
                },
                error => alert(error.message),
                { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
            );
            watchID = navigator.geolocation.watchPosition(position => {
                currentLatitude = JSON.stringify(JSON.stringify(position.coords.latitude));
                currentLongitude = JSON.stringify(JSON.stringify(position.coords.longitude));
                // currentLatitude = currentLatitude;
                // currentLongitude = currentLongitude;
            });
            
            // let location = await Location.getCurrentPositionAsync({});
            // setLocation(location);
        })();
        // return() => {
        //     navigator.geolocation.clearWatch(watchID);
        // }
    }, []);

    // let text="Loading...";
    // if (errorMsg){
    //     text = errorMsg;
    // } else if (location){
    //     text = JSON.stringify(location);
    // }

    return(
        
        <SafeAreaView>
            
            <MapView
                style={{ height, width: mapWidth }}
                region={{
                    latitude: currentLatitude,
                    longitude: currentLongitude,
                    latitudeDelta: 0.005,
                    longitudeDelta: 0.005
                }}
                loadingEnabled={true}
                provider={PROVIDER_GOOGLE}
                showsUserLocation={true}
                showsMyLocationButton={true}
                
                onMapReady={() => {
                    updateMapStyle()
                }}
            ></MapView>
            <View style={styles.sectionStyle}>
                <Stopwatch
                    laps
                    start={isStopwatchStart}
                    options={options}
                    getTime={(time) => {
                        console.log(time);
                    }}
                />     
            </View>
            
            <View style={styles.buttonArea} >
                <TouchableOpacity 
                    onPress={() => {  }}>
                        <MaterialCommunityIcons name="emoticon-poop" size={60} color="#F3C757" />
                </TouchableOpacity>
                <TouchableOpacity 
                    onPress={() => {
                        setIsStopwatchStart(!isStopwatchStart);
                        setResetStopwatch(false);
                    }}
                >
                     {!isStopwatchStart ? <Icon name="play-circle" size={90} color="#F3C757"></Icon> : <Icon name="stop-circle" size={85} color="#F3C757"></Icon>}
                </TouchableOpacity>
                <TouchableOpacity
                    onPress={() => navigation.navigate('camera') }>
                    <Text>
                        <AntDesign name="camerao" size={60} color="#F3C757" />
                    </Text>
                </TouchableOpacity>
            </View>
        </SafeAreaView>
    );
}

const styles = StyleSheet.create({
    sectionStyle: {
        marginTop: 20,
        alignItems: 'center',
        justifyContent: 'center'
    },
    buttonArea:{
        flexDirection: 'row',
        marginTop: 70,
        justifyContent: 'space-evenly',
        alignItems: 'center'
    },
});

const options = {
    container: {
    backgroundColor: '#FFFFFF',
    padding: 5,
    borderRadius: 5,
    width: 200,
    alignItems: 'center',
    },
    text: {
    fontSize: 35,
    color: 'black',
    marginLeft: 7,
    },
};

export default ChannelCreation;

I think you should set initialregion parameter prop to MapView component. it should look something like this.

   <MapView
    style={{height, width: mapWidth}}
    region={{
      latitude: currentLatitude,
      longitude: currentLongitude,
      latitudeDelta: 0.005,
      longitudeDelta: 0.005,
    }}
    initialRegion={initialRegion}
    loadingEnabled={true}
    provider={PROVIDER_GOOGLE}
    showsUserLocation={true}
    showsMyLocationButton={true}
    onMapReady={() => {
      updateMapStyle();
    }}></MapView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM