2016-06-30 9 views
13

Ho creato mappe in react-native con riferimento a https://github.com/lelandrichardson/react-native-maps la mappa è stata creata ma voglio rilevare la posizione automatica usando gps. Ecco il codice che esegue il rendering della mappa con latitudine e longitudine statiche. Ecco il mio codice aggiornato. Ma ancora non rende la posizione perfettacome creare mappe che rilevano la localizzazione automatica in React-Native

getInitialState() { 
    return { 
     initialPosition: 'unknown', 
     lastPosition: 'unknown', 
    }; 
    }, 

    componentDidMount() { 
    navigator.geolocation.getCurrentPosition(
     (position) => { 
     var initialPosition = JSON.stringify(position); 
     this.setState({initialPosition}); 
     }, 
     {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000} 
    ); 
    this.watchID = navigator.geolocation.watchPosition((position) => { 
     var lastPosition = JSON.stringify(position); 
     this.setState({lastPosition}); 
    }); 
    }, 

    componentWillUnmount() { 
    navigator.geolocation.clearWatch(this.watchID); 
    }, 

    render() { 
    return (
     <View style={styles.container}> 
     <MapView 
      ref="map" 
      mapType="terrain" 
      style={styles.map} 
      initialPosition={this.state.initialPosition} 
      lastPosition={this.state.lastPosition} 
     > 
     </MapView> 
     </View> 

puoi correggerlo?

Grazie in anticipo

risposta

9

È possibile farlo usando React-native geolocalizzazione:
https://facebook.github.io/react-native/docs/geolocation.html

C'è già un buon esempio non su come si può fare questo:

componentDidMount: function() { 
    navigator.geolocation.getCurrentPosition(
    (position) => { 
     var initialPosition = JSON.stringify(position); 
     this.setState({initialPosition}); 
    }, 
    (error) => alert(error.message), 
    {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000} 
); 
    this.watchID = navigator.geolocation.watchPosition((position) => { 
    var lastPosition = JSON.stringify(position); 
    this.setState({lastPosition}); 
    }); 
} 

È ora hai la initialPosition (latitudine e longitudine), usalo invece del tuo valore hard coded. WatchPosition richiama la richiamata di successo ogni volta che cambia la posizione.

Attualmente sto usando questo per trovare ristoranti locali nella nostra app.


Risposta Aggiornato:

Sto usando Genymotion emulatore per eseguire questo. Se esegui questo codice anche su Genymotion, assicurati di aver installato il supporto di Google Play, altrimenti le mappe native non funzioneranno. Non è necessario eseguire questo passaggio se si utilizza un dispositivo fisico.

https://github.com/codepath/android_guides/wiki/Genymotion-2.0-Emulators-with-Google-Play-support

Per quanto riguarda Geolocation, assicurati di aver aggiunto il permesso ACCESS_FINE_LOCATION nel AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

altrimenti si ottiene un errore: "Sembra che l'applicazione doesn' Ho il permesso di accedere alla posizione. "

Inoltre, assicurarsi che il proprio GPS/Wifi/Dati sia abilitato, altrimenti il ​​dispositivo non può recuperare la posizione corrente.

var React = require('react'); 
var ReactNative = require('react-native'); 
var { 
    StyleSheet, 
    PropTypes, 
    View, 
    Text, 
    Dimensions, 
    TouchableOpacity, 
} = ReactNative; 

var MapView = require('react-native-maps'); 

var { width, height } = Dimensions.get('window'); 
const ASPECT_RATIO = width/height; 

// (Initial Static Location) Mumbai 
const LATITUDE = 19.0760; 
const LONGITUDE = 72.8777; 

const LATITUDE_DELTA = 0.01; 
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; 

var CustomMap = React.createClass({ 
    getInitialState() { 
    return { 
     region: { 
     latitude: LATITUDE, 
     longitude: LONGITUDE, 
     latitudeDelta: LATITUDE_DELTA, 
     longitudeDelta: LONGITUDE_DELTA 
     }, 
    }; 
    }, 

    componentDidMount: function() { 
    navigator.geolocation.getCurrentPosition(
     (position) => { 
     this.setState({ 
      region: { 
      latitude: position.coords.latitude, 
      longitude: position.coords.longitude, 
      latitudeDelta: LATITUDE_DELTA, 
      longitudeDelta: LONGITUDE_DELTA 
      } 
     }); 
     }, 
     (error) => alert(error.message), 
     {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000} 
    ); 

    this.watchID = navigator.geolocation.watchPosition((position) => { 
     const newRegion = { 
     latitude: position.coords.latitude, 
     longitude: position.coords.longitude, 
     latitudeDelta: LATITUDE_DELTA, 
     longitudeDelta: LONGITUDE_DELTA 
     } 

     this.onRegionChange(newRegion); 
    }); 
    }, 

    componentWillUnmount: function() { 
    navigator.geolocation.clearWatch(this.watchID); 
    }, 

    onRegionChange(region) { 
    this.setState({ region }); 
    }, 

    render() { 
    return (
     <View style={styles.container}> 
     <MapView 
      ref="map" 
      mapType="terrain" 
      style={styles.map} 
      region={this.state.region} 
      onRegionChange={this.onRegionChange} 
     > 
     </MapView> 
     <View style={styles.bubble}> 
      <Text style={{ textAlign: 'center'}}> 
      {`${this.state.region.latitude.toPrecision(7)}, ${this.state.region.longitude.toPrecision(7)}`} 
      </Text> 
     </View> 
     </View> 
    ); 
    }, 
}); 

var styles = StyleSheet.create({ 
    container: { 
    position: 'absolute', 
    top: 0, 
    left: 0, 
    right: 0, 
    bottom: 0, 
    justifyContent: 'flex-end', 
    alignItems: 'center', 
    }, 
    map: { 
    position: 'absolute', 
    top: 0, 
    left: 0, 
    right: 0, 
    bottom: 0, 
    }, 
    bubble: { 
    backgroundColor: 'rgba(255,255,255,0.7)', 
    paddingHorizontal: 18, 
    paddingVertical: 12, 
    borderRadius: 20, 
    }, 
}); 

module.exports = CustomMap; 

L'esecuzione del codice di cui sopra, si dovrebbe trovare che la posizione statica originaria (Mumbai) viene sovrascritto con la posizione attuale dal dispositivo attraverso componentDidMount quando getCurrentPosition viene chiamato.

Se avete bisogno di tenere traccia delle modifiche di posizione, usare watchPosition in combinazione con onRegionChange, altrimenti se avete solo bisogno di ottenere la posizione iniziale rimuovere watchPosition passo.

+0

hey ho aggiornato il mio codice lo si può vedere come domanda ma la posizione perfetta non è ancora resa – atif

+0

stai usando genomotion?Ti sei assicurato che il tuo GPS sia abilitato? Hai provato la posizione di registrazione della console, per assicurarti che getCurrentPosition restituisca una posizione valida? Ho anche notato che non si gestiscono errori nella chiamata a getCurrentPosition. Prova ad aggiungere "(errore) => avviso (error.message)," per vedere se ricevi degli errori. – Antoni4

+0

Sto usando un dispositivo fisico per testare. ho rimosso la parte dell'errore provata aggiungendola ma nessun successo. il mio codice è corretto? – atif

Problemi correlati