Eu fiz um código para obter a geolocalização do celular, apresentar está no maps e retornar o endereço
Assim tenho no arquivo ./services/location.js
:
const location = { getGeocode: (latitude, longitude, callback) => { axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ latitude +','+ longitude + __API_KEY__) .then(response => { callback(response.data.results[0]) }).catch((error) => { console.log( error.message ) }); }, getPosition: (callback) => { navigator.geolocation.getCurrentPosition( (position) => { callback(position.coords) }, (error) => { console.log(error) callback(error) }, { enableHighAccuracy: true, timeout: 20000 }, ); } };
Utilizo este no arquivo Location.js
no componentWillMount
:
componentWillMount() { location.getPosition((res) => { if(res.code !== undefined) { this.setState({ place: 'Houve um problema ao tentar determinar sua localização, verifique se a localização (GPS) está ativada', visibleModal: 1 }) }else{ this.setState({ latitude: res.latitude, longitude: res.longitude, }, () => { this.getInitialState( this.state.latitude, this.state.longitude, this.state.latitudeDelta, this.state.longitudeDelta ), location.getGeocode( this.state.latitude, this.state.longitude, (res) => { this.setState({ address: res.address_components[1].long_name, number: res.address_components[0].long_name, neighborhood: res.address_components[2].long_name, city: res.address_components[3].long_name }, () => this.setPlace()) }, )} ) } }); }
E apresento no mapa através das seguintes funções:
getInitialState = (latitude, longitude, latitudeDelta, longitudeDelta) => { this.setState({ initialRegion: { latitude, longitude, latitudeDelta, longitudeDelta, }, }); } onRegionChange = (initialRegion) => { this.setState({ initialRegion }); } _renderMap = (latitude, longitude) => ( <MapView initialRegion={this.state.initialRegion} onRegionChange={this.onRegionChange} style={styles.map} > <MapView.Marker coordinate={{ latitude: latitude, longitude: longitude, }} /> </MapView> )
Normalmente, no primeiro acesso o aplicativo apresenta os dados da ultima posição onde foi utilizado algum serviço de localização, após reiniciar o APP este apresenta corretamente, o que poderia ser?