Issue
How do i go about this? I am trying to render the contents of Initial region, so that once the Application Loads it automatically gets the Longitude and Latitude of the Location and put on the screen. I am just a bit confused as to what and how to go about it, My source code is given thus
import React, { Component } from 'react';
import { View, Text , StyleSheet, Dimensions } from 'react-native';
import MapView from 'react-native-maps';
export default class HomePage extends Component {
constructor(props) {
super(props);
}
componentDidMount(){
navigator.geolocation.getCurrentPosition((position)=>{
var lat = parseFloat(position.coords.latitude)
var long = parseFloat(position.coords.longitude)
var initialRegion ={
latitude: lat,
longitude: long,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}
this.setState({ initialRegion: initialRegion })
},
(error) => aalert(JSON.stringify(error)),
{
enableHighAccuracy: true, timeout: 20000, maximumAge: 1000
});
}
render() {
return (
<View style={styles.container}>
<MapView style={styles.map}
initialRegion={this.state.initialRegion}
showsUserLocation={true}>
</MapView>
</View>
);
}
}
const styles=StyleSheet.create({
container:{
flex: 1,
},mapContainer: {
flex: 1,
},
map: {
flex: 1,
width: Dimensions.get("window").width,
height: Dimensions.get("window").height,
}
});
Any candid advice as to how I can do something like that? Kindly assist.
Solution
I would guess the your map loads with no initialRegion
as you are doing a request after the first render (componentDidMount) you may try to prevent the map from loading before you have the necessary information, I've also started your state on constructor. The code would look like this:
import React, { Component } from 'react';
import { View, Text , StyleSheet, Dimensions } from 'react-native';
import MapView from 'react-native-maps';
export default class HomePage extends Component {
constructor(props) {
super(props);
this.state = {
initialRegion: null
}
}
componentDidMount(){
navigator.geolocation.getCurrentPosition((position)=>{
var lat = parseFloat(position.coords.latitude)
var long = parseFloat(position.coords.longitude)
var initialRegion = {
latitude: lat,
longitude: long,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}
this.setState({ initialRegion: initialRegion })
},
(error) => aalert(JSON.stringify(error)),
{
enableHighAccuracy: true, timeout: 20000, maximumAge: 1000
});
}
render() {
return (
<View style={styles.container}>
{this.state.initialRegion !== null && (
<MapView style={styles.map}
initialRegion={this.state.initialRegion}
showsUserLocation={true} />
)}
</View>
);
}
}
Wish success on your project.
Answered By - Luís C Meireles
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.