Android : Sometimes Google Map showing wrong current location - android

I am using react-native-maps to show the map
I am getting my current location as follows:
navigator.geolocation.getCurrentPosition(
position => {
region = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: this.state.position.latitudeDelta,
longitudeDelta: this.state.position.longitudeDelta
}
this.setState(
{
position: {
latitude: region.latitude,
longitude: region.longitude,
latitudeDelta: region.latitudeDelta,
longitudeDelta: region.longitudeDelta,
error: null
}
})
})
But some times it showing the before location that I am in
Can any one suggest how to solve this by code
Thank you

You should consider using the parameter 'maximumAge'. e.g.
navigator.geolocation.getCurrentPosition(position => {
region: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: this.state.position.latitudeDelta,
longitudeDelta: this.state.position.longitudeDelta
}
this.setState(
{
position: {
latitude: region.latitude,
longitude: region.longitude,
latitudeDelta: region.latitudeDelta,
longitudeDelta: region.longitudeDelta,
error: null
}
})
}, err => {
console.log(err)
alert('fetching the position failed')
}, {enableHighAccuracy: false, timeout: 20000, maximumAge: 0})
As per MDN documentation :
The PositionOptions.maximumAge property is a positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to Infinity the device must return a cached position regardless of its age.

Related

How To Loop Through Array Inside a MapView object

I have a MapView that I want to add Markers to. I can successfully add Markers individually but I want to loop through an array of coordinates and add a marker for each location in the array. Whenever trying to run this code, I get an "Unexpected Token" error where the for loop begins. I have read suggestions about using the .map function on the array but that does not seem to work for me either. Any help would be highly appreciated.
const ViewNearbyScreen = ({
navigation, route
}) => {
const points = [
{
name: "Wendys",
lat: 37.4319983,
lng: -122.094,
},
{
name: "Taco Bell",
lat: 37.4419983,
lng: -122.104,
},
{
name: "Whataburger",
lat: 37.4519983,
lng: -122.114,
},
];
return (
<MapView
provider={PROVIDER_GOOGLE}
style={{flex: 1}}
region={{
latitude: 37.4219983,
longitude: -122.084,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}}
ref={mapRef}
showsUserLocation>
{for(let i = 0; i < 3; i++) {
<Marker
coordinate={{
latitude: points[{i}].lat,
longitude: points[{i}].lng,
}}
title={points[{i}].name}
/>
}}
</MapView>
)
};
You can use the Array Map method to loop through the array elements.
points.map(item => { // each point in points array
return (
<Marker
coordinate={{
latitude: item.lat,
longitude: item.lng,
}}
title={item.name}
/>
)
})
The reason the map method wasn't working for you might be that you forgot to return your jsx.

how to get live geo location in react native

I've added MapView into my app but i want to initialize the region with the current user's live location, The code on the emulator changes the initial region to the location of google's HQ in CA (I know that's normal and i can change the emulator's location in settings) but on my own phone, the initial region doesn't change at all.
using the GEO location api preferred by react native:
const [region, setRegion] = useState({
latitude: -1.951670,
longitude: 30.157518,
latitudeDelta: 0.015,
longitudeDelta: 0.015,
})
useEffect(() => {
let currentLocation = true;
let newRegion = { latitude: null, longitude: null, latitudeDelta: null, longitudeDelta: null };
newRegion.longitudeDelta = region.longitudeDelta;
newRegion.latitudeDelta = region.latitudeDelta;
Geolocation.getCurrentPosition((info) => {
newRegion.latitude = info.coords.latitude
newRegion.longitude = info.coords.longitude;
},
(error) => {
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
)
//To make sure no null is still present in the newReion obj
for (var key in newRegion) {
if (!newRegion[key]) {
currentLocation = false;
break;
}
}
if (currentLocation) {
setRegion(newRegion);
}
}, [])
//Map view implementation:
<MapView
provider={PROVIDER_GOOGLE}
ref={map => _map = map}
showsUserLocation={true}
style={styles.map}
initialRegion={initialPosition}
onRegionChangeComplete={(region) => setInitialPosition(region)}
/>

React native location when device's location in turned off

My android app crashes if device's location is turned off when I request permission to get location . how can I fix this? here is my getLocation() function:
getLocation = () => {
try {
navigator
.geolocation
.getCurrentPosition(position => {
const location = JSON.stringify(position);
this.writeItemToStorage(position.coords.latitude,position.coords.longitude);
this.setState({location: location, latitude: position.coords.latitude, longitude: position.coords.longitude});
}, error => Alert.alert(error.message), {
enableHighAccuracy: false,
timeout: 20000,
maximumAge: 10000
});
} catch(e) {
alert(e);
}
}
I set the lat and long in asyncstorage

Some custom markers do not appear on Android react-native-maps

In our app, we are obtaining the user location when he logs in (click login -> get location -> save location in redux -> navigate to home screen). When the Home component mounts, it should use the location to get data from the area around the user.
In iOS, all markers render correctly but in Android devices, not all markers are rendered, only some of them (and oddly enough all of them are image1 or image2).
It is only when we call the getDataFromRegion function again that all markers render correctly. Any idea of what we are doing wrong?
class Login extends Component {
handleLogin = (u, p) => {
getLocation(location => {
let region = {
latitude: location.coords.latitude,
longitude: location.coords.longitude,
latitudeDelta: 0.06,
longitudeDelta: 0.06
}
/* save location in redux */
this.props.setLocation(region)
login(u, p).then(() => _gotoHome())
})
}
}
class Home extends Component {
componentWillMount() {
if(this.props.location !== undefined) {
initialRegion = {
latitude: this.props.location.latitude,
longitude: this.props.location.longitude,
latitudeDelta: 0.06,
longitudeDelta: 0.06
}
}
}
componentDidMount() {
/* set data in redux */
this.getDataFromRegion(initialRegion)
}
render() {
this.props.data.map((data, index) => data.visible ? <CustomMarker key={index} data={data}/> : null)
}
}
class CustomMarker extends Component {
render() {
const {data} = this.props
const coords = { latitude: data.lat, longitude: data.lng }
return (
<MapView.Marker
coordinate={coords}
onLoad={() => this.forceUpdate()}
tracksViewChanges={Platform.OS === 'android' ? false : true}
>
<Image
onLoad={() => this.forceUpdate()}
source={data.a === '0' ? image1 : image2}
style={{width: 60, height: 60}}
/>
</MapView.Marker>
)
}
}
It seems like removing the Image component and use the MapView.Marker prop image got it working. Also, rendering a dummy MapView.Marker with opacity: 0 inside the MapView solved the problem of appearing the default markers at the first render call.

React Native - Accurate Current location(Latitude, Longitude)

Hi I am using below code to get the accurate current latitude and longitude
but i am not able to get the accurate location, So can anybody suggest me how to get accurate current latitude and longitude in react native(Android and iOS).
this.watchID = navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
// { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
}
Thanks in Advance.
To get accurate Location and longitude in android manifest you can declare
AndroidManifes.xml
<uses-permission android:name="android.permisssion.ACCESS_FINE_LOCATION"></uses-permission>
try this library react-native-geolocation-service
hope this help!

Categories

Resources