How to get current location using react-native-maps
Asked Answered
T

7

11

Im trying to render a map at the current user geolocation on android device, using react-native maps.

Here is what i've got so far:

import React, { Component } from 'react';

import {
  View,
  StyleSheet,
  Dimensions,
} from 'react-native';

import MapView from 'react-native-maps';

const {width, height} = Dimensions.get('window')

const SCREEN_HEIGHT = height
const SCREEN_WIDTH = width
const ASPECT_RATIO = width / height
const LATITUDE_DELTA = 0.0922
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO

class MapComponent extends Component {
  constructor() {
    super()
    this.state = {
      initialPosition: {
        latitude: 0,
        longitude: 0,
        latitudeDelta: 0,
        longitudeDelta: 0,
      },
    }
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition((position) => {
      var lat = parseFloat(position.coords.latitude)
      var long = parseFloat(position.coords.longitude)

      var initialRegion = {
        latitude: lat,
        longitude: long,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      }

      this.setState({initialPosition: initialRegion})
    },
    (error) => alert(JSON.stringify(error)),
    {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000});
  }


  renderScreen = () => {
      return (
        <View style={styles.container}>
          <MapView
            style={styles.map}
            initialRegion={this.state.initialPosition}/>
        </View>
      );
  }

  render() {
    return (
      this.renderScreen()
    );
  }
}

const 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,
  },
});

export default MapComponent;

The map renders, but not in current device geolocation, as expected. (it renders in the middle of the ocean)

The permissions are already set at AndroidManifest.xml as:

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

After 20 seconds, i get an alert saying, "Location request timed out" "code 3"

What i'm doing wrong?

Thereabouts answered 29/11, 2017 at 17:31 Comment(2)
Geolocation.getCurrentPosition((info) => { let lat = info.coords.latitude; let long = info.coords.longitude; console.log(lat); console.log(long); var initialRegion = { latitude: lat, longitude: long, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }; this.setState({ initialPosition: initialRegion }); });Songstress
Use this function it will solve your problemSongstress
M
8

I'm not sure but there is an issue ("Geolocation timed out, code 3") which looks related

For anyone else struggling with this issue on android, try removing the maximumAge: 2000 option parameter. This option was causing geolocation to either timeout or crash the app.

Micromho answered 29/11, 2017 at 17:42 Comment(0)
I
7
import React, {useState, useEffect} from 'react';
import {StyleSheet, Text} from 'react-native';
import MapView, {Marker} 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,
    });
  },(err) => {
    console.log(err);
  });
}, []);

  return (
    <MapView
      style={styles.map}
      initialRegion={position}
      showsUserLocation={true}
      showsMyLocationButton={true}
      followsUserLocation={true}
      showsCompass={true}
      scrollEnabled={true}
      zoomEnabled={true}
      pitchEnabled={true}
      rotateEnabled={true}>
       <Marker
       title='Yor are here'
       description='This is a description'
       coordinate={position}/>
       </MapView>
  );
};

const styles = StyleSheet.create({
  map: {
    ...StyleSheet.absoluteFillObject,
  },
});


export default App;
Irita answered 27/4, 2022 at 6:51 Comment(1)
this is working. also add permissions <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />Goatee
T
1

It's working perfectly in mine. Only change I made was in StyleSheet.

container: {
    position: 'absolute',
    height : SCREEN_HEIGHT,
    width : SCREEN_WIDTH,
    justifyContent: 'flex-end',
    alignItems: 'center',
}

Thereafter, it renders my location. You can add marker after that to show your location.

Tyrothricin answered 28/10, 2018 at 7:55 Comment(0)
E
0

navigator.geolocation.getCurrentPosition() is deprecated.
Use @react-native-community/geolocation instead.

npm install @react-native-community/geolocation --save
Everard answered 13/4, 2020 at 11:10 Comment(2)
react-native-geolocation-service is much betterParasympathetic
@react-native-community/geolocation seems to be deprecated, upvote for @ggDeGreat.Blackbird
S
-1

This is what worked for me. the third option is what was creating the prob.

navigator.geolocation.getCurrentPosition() =>{

},
 err => {

},
{ enableHighAccuracy: false, timeout: 20000}, //this worked for me
Styrax answered 6/3, 2019 at 6:14 Comment(1)
Would be helpful if you can provider where the component comes from?Bearing
S
-1

1.npm install @react-native-community/geolocation --save
2.import Geolocation from '@react-native-community/geolocation';
3.navigator.geolocation.getCurrentPosition => Geolocation.getCurrentPosition

Skidmore answered 20/8, 2020 at 10:44 Comment(1)
It would be nice if you could explain in a little more detail how your described step help answering the question.Pylorectomy
S
-1
import React, { Component } from "react";
// global.currentScreenIndex = 'Dashboard';
//Import all required component
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Image,
  Modal,
  TouchableHighlight,
  StatusBar,
  FlatList,
  ActivityIndicator,
  Button,
  NetInfo,
} from "react-native";
import MapView, { Marker } from "react-native-maps";
import Geolocation from "@react-native-community/geolocation";

const MyStatusBar = ({ backgroundColor, ...props }) => (
  <View style={[styles.statusBar, { backgroundColor }]}>
    <StatusBar translucent backgroundColor={backgroundColor} {...props} />
  </View>
);
   

class Dashboard extends Component {
  constructor() {
    super();
    this.state = {
      initialPosition: {
        latitude: 0,
        longitude: 0,
        latitudeDelta: 0,
        longitudeDelta: 0,
      },
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    Geolocation.getCurrentPosition((info) => {
      let lat = info.coords.latitude;
      let long = info.coords.longitude;

      console.log(lat);
      console.log(long);
      var initialRegion = {
        latitude: lat,
        longitude: long,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
      };
      this.setState({ initialPosition: initialRegion });
    });
  }

  render() {
    const { modalVisible } = this.state;
    const { navigate } = this.props.navigation;
    // const token_data = token_value();
    // console.log("token_homes_2st"+token_data);

    return (
      <View style={styles.container}>
        <MapView
          style={styles.map}
          initialRegion={this.state.initialPosition}
          showsUserLocation={true}
        />
      </View>
    );
  }
}
export default Dashboard;

const styles = StyleSheet.create({
  container: {
    justifyContent: "center",
    fontWeight: "400",
    color: "#000",
    fontFamily:
      "Inter UI,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif",
  },

  map: {
    height: 400,
    width: 400,
    justifyContent: "flex-end",
    alignItems: "center",
  },
});
Songstress answered 18/1, 2022 at 11:25 Comment(1)
Please read How to Answer and edit your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post.Steamroller

© 2022 - 2024 — McMap. All rights reserved.