Reputation: 1081
I was trying get the current location using react-native-maps
. This is my following code :
import MapView from 'react-native-maps';
import Geolocation from '@react-native-community/geolocation';
const [position, setPosition] = useState({
latitude: 10,
longitude: 10,
latitudeDelta: 0.001,
longitudeDelta: 0.001,
});
useEffect(() => {
Geolocation.getCurrentPosition(success, error, options);
}, []);
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0,
};
function success(pos) {
var crd = pos.coords;
setPosition({
latitude: crd.latitude,
longitude: crd.longitude,
latitudeDelta: 0.0421,
longitudeDelta: 0.0421,
});
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
return (
<MapView
style={styles.map}
initialRegion={position}
showsUserLocation={true}
>
</MapView>
Now if I remove the property initialRegion
, the map is working perfectly fine. But with the above code, I am getting a white screen without any error.
Any help will be appreciated.
Upvotes: 2
Views: 8898
Reputation: 15462
I think the problem with your code is that getCurrentPosition
is failing and since your initial coordinates inside position
are very zoomed in, it looks like it isn't showing anything.
Also make sure the google maps API is enabled and react-native-maps is configured correctly.
Here is how I got it working:
import React, {useState, useEffect} from 'react';
import {StyleSheet} from 'react-native';
import MapView from 'react-native-maps';
import Geolocation from '@react-native-community/geolocation';
const App = () => {
const [position, setPosition] = useState({
latitude: 10,
longitude: 10,
latitudeDelta: 0.001,
longitudeDelta: 0.001,
});
useEffect(() => {
Geolocation.getCurrentPosition((pos) => {
const crd = pos.coords;
setPosition({
latitude: crd.latitude,
longitude: crd.longitude,
latitudeDelta: 0.0421,
longitudeDelta: 0.0421,
});
}).catch((err) => {
console.log(err);
});
}, []);
return (
<MapView
style={styles.map}
initialRegion={position}
showsUserLocation={true}
/>
);
};
const styles = StyleSheet.create({
map: {
...StyleSheet.absoluteFillObject,
},
});
export default App;
Upvotes: 2