voici mon code pour obtenir la position actuelle de l'appareil.
{ "timestamp":1551594077000, "mocked":false, "coords":{ "heading":0, "longitude":80.4380389, "speed":0, "altitude":-78, "latitude":6.0140343, "accuracy":21.238000869750977 }
ce que je veux faire, c'est transmettre la latitude et la logtitude à MapView. mais ça ne fonctionne pas.
la sortie de
console.log (text)
est
import React, { Component } from 'react'; import { Platform, Text, View, StyleSheet, FlatList } from 'react-native'; import { Constants, Location, Permissions, MapView } from 'expo'; export default class Home extends Component { state = { location: null, errorMessage: null, }; componentWillMount() { if (Platform.OS === 'android' && !Constants.isDevice) { this.setState({ errorMessage: 'Oops, this will not work on Sketch in an Android emulator. Try it on your device!', }); } else { this._getLocationAsync(); } } _getLocationAsync = async () => { let { status } = await Permissions.askAsync(Permissions.LOCATION); if (status !== 'granted') { this.setState({ errorMessage: 'Permission to access location was denied', }); } let location = await Location.getCurrentPositionAsync({ enableHighAccuracy: true }); this.setState({ location }); }; render() { let text = 'Waiting..'; if (this.state.errorMessage) { text = this.state.errorMessage; } else if (this.state.location) { text = JSON.stringify(this.state.location); } console.log(text) return ( <MapView style={{ flex: 1 }} region={{ latitude: text.coords.latitude, longitude: text.coords.longitude, latitudeDelta: 0.1, longitudeDelta: 0.1, }} /> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', }, paragraph: { margin: 24, fontSize: 18, textAlign: 'center', }, });
Je lance ce projet sur mon téléphone intelligent (galaxy j5 10) en utilisant l'application expo. toutes les autorisations de localisation sont accordées à l'application et ne fonctionnent toujours pas. J'ai essayé beaucoup de documentations, mais cela ne fonctionne pas. comment puis-je corriger cela.
3 Réponses :
Il semble que vous ayez converti l'objet en une chaîne avec JSON.stringify (emplacement).
Vous ne pouvez pas accéder aux propriétés d'une chaîne avec l'extension. opérateur.
Essayez plutôt de le laisser en tant qu'objet et de transmettre les valeurs au composant de carte.
Vous convertissez l'emplacement en chaîne JSON. Les coordonnées latlong sont supposées être des valeurs à virgule flottante. Essayez ceci:
state = { region: { longitude: -122.0840052, //Replace with any initial value here latitude: 37.4220181, longitudeDelta: 0.04, latitudeDelta: 0.09 } }; let { coords } = await Location.getCurrentPositionAsync({}); this.setState({ region: { longitude: coords.longitude, latitude: coords.latitude, longitudeDelta: 0.04, latitudeDelta: 0.09 } }); <MapView region={this.state.region} />
J'espère que cela vous aidera!
Votre erreur est causée par votre méthode de rendu:
export default class Home extends Component { state = { location: null, errorMessage: null, loaded: false }; // componentWillMount has been deprecated, use componentDidMount instead componentDidMount () { if (Platform.OS === 'android' && !Constants.isDevice) { this.setState({ errorMessage: 'Oops, this will not work on Sketch in an Android emulator. Try it on your device!', loaded:true }); } else { this._getLocationAsync(); } } _getLocationAsync = async () => { let { status } = await Permissions.askAsync(Permissions.LOCATION); if (status !== 'granted') { this.setState({ errorMessage: 'Permission to access location was denied', loaded: true }); } else { // only check the location if it has been granted // you also may want to wrap this in a try/catch as async functions can throw let location = await Location.getCurrentPositionAsync({ enableHighAccuracy: true }); this.setState({ location, loaded: true, errorMessage: null }); } }; render () { // check to see if we have loaded if (this.state.loaded) { // if we have an error message show it if (this.state.errorMessage) { return ( <View style={styles.container}> <Text>{JSON.stringify(this.state.errorMessage)}</Text> </View> ); } else if (this.state.location) { // if we have a location show it return ( <MapView style={{ flex: 1 }} region={{ latitude: this.state.location.coords.latitude, longitude: this.state.location.coords.longitude, latitudeDelta: 0.1, longitudeDelta: 0.1 }} /> ); } } else { // if we haven't loaded show a waiting placeholder return ( <View style={styles.container}> <Text>Waiting...</Text> </View> ); } } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1' }, paragraph: { margin: 24, fontSize: 18, textAlign: 'center' } });
Lorsque this.state.errorMessage
est nul, vous ne définissez pas de valeur pour le this.state.location
afin que votre MapView
essaie d'utiliser la valeur que vous avez définie comme text
, ce qui ne fonctionne pas car this.state. location
est nul et générera une erreur si vous essayez d'accéder à des valeurs dessus.
Lorsque vous avez un emplacement, vous utilisez JSON.stringify
pour convertir l'objet d'emplacement en une chaîne, mais cela vous empêche d'accéder aux propriétés de l'objet.
Lorsque les deux this.state.errorMessage
et this.state.location
sont nuls, votre texte
est juste une chaîne. cela entraînera une erreur de MapView
car vous essayez d'accéder aux propriétés d'objet sur une chaîne.
Vous devriez faire quelque chose comme ceci:
_getLocationAsync
Voici le refactor
render() { let text = 'Waiting..'; if (this.state.errorMessage) { text = this.state.errorMessage; } else if (this.state.location) { text = JSON.stringify(this.state.location); } console.log(text) return ( <MapView style={{ flex: 1 }} region={{ latitude: text.coords.latitude, longitude: text.coords.longitude, latitudeDelta: 0.1, longitudeDelta: 0.1, }} /> ); }