Get current location, latitude and longitude in ReactNative using react-native-maps
Asked Answered
K

3

34

I am developing a map location. When I click in some particular place I get the latitude and longitude, but not the current location, latitude and longitude.

I don't know how to find out.

How can I get them and how can I put the marker at that position?

Here is my code:

class Maps extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      region: {
        latitude:       LATITUDE,
        longitude:      LONGITUDE,
        latitudeDelta:  LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      },
      marker: {
        latlng:{
          latitude:       null,
          longitude:      null,
          latitudeDelta:  LATITUDE_DELTA,
          longitudeDelta: LONGITUDE_DELTA
        }
      }
    }
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition (
      (position) => { alert("value:" + position) },
      (error)    => { console.log(error) },
      {
        enableHighAccuracy: true,
        timeout:            20000,
        maximumAge:         10000
      }
    )
  }

  onMapPress(e) {
    alert("coordinates:" + JSON.stringify(e.nativeEvent.coordinate))
      this.setState({
        marker: [{ coordinate: e.nativeEvent.coordinate }]
      })
    }

  render() {
    return (
      <View style={styles.container}>
        <View style={{flexGrow:1}}>
          <MapView
            ref="map"
            provider={this.props.provider}
            style={styles.map}
            onPress={this.onMapPress.bind(this)}
            provider = {PROVIDER_DEFAULT}
            mapType="standard"
            zoomEnabled={true}
            pitchEnabled={true}
            showsUserLocation={true}
            followsUserLocation={true}
            showsCompass={true}
            showsBuildings={true}
            showsTraffic={true}
            showsIndoors={true}>
          </MapView>
        </View>
      </View>
    )
  }
}
Km answered 3/4, 2017 at 5:8 Comment(1)
follow this link npmjs.com/package/@react-native-community/geolocationBoyles
F
40

I did it following these steps using [email protected] and react-native-maps@^0.13.1 and using [email protected] and react-native-maps@^0.15.2 at the date:

Set a mapRegion object in the state, the last longitude and the last latitude as null:

state = {
  mapRegion: null,
  lastLat: null,
  lastLong: null,
}

Then within your componentDidMount() function watch for each change in the current position:

  componentDidMount() {
    this.watchID = navigator.geolocation.watchPosition((position) => {
      ...
    });
  }

When there are changes update them in your this.state.mapRegion, passing the actual coords and the delta values (mine can be different to yours, so adapt them):

  componentDidMount() {
    this.watchID = navigator.geolocation.watchPosition((position) => {
      // Create the object to update this.state.mapRegion through the onRegionChange function
      let region = {
        latitude:       position.coords.latitude,
        longitude:      position.coords.longitude,
        latitudeDelta:  0.00922*1.5,
        longitudeDelta: 0.00421*1.5
      }
      this.onRegionChange(region, region.latitude, region.longitude);
    }, (error)=>console.log(error));
  }

Then you need the onRegionChange() function, that's being used to "set" new values to your elements within the componentDidMount() function:

  onRegionChange(region, lastLat, lastLong) {
    this.setState({
      mapRegion: region,
      // If there are no new values set the current ones
      lastLat: lastLat || this.state.lastLat,
      lastLong: lastLong || this.state.lastLong
    });
  }

Unmount the geolocation on componentWillUnmount():

  componentWillUnmount() {
    navigator.geolocation.clearWatch(this.watchID);
  }

And render the MapView passing your current mapRegion object, the MapView.Marker inside of it is just to show you the current latitude and longitude when they change:

  render() {
    return (
      <View style={{flex: 1}}>
        <MapView
          style={styles.map}
          region={this.state.mapRegion}
          showsUserLocation={true}
          followUserLocation={true}
          onRegionChange={this.onRegionChange.bind(this)}>
          <MapView.Marker
            coordinate={{
              latitude: (this.state.lastLat + 0.00050) || -36.82339,
              longitude: (this.state.lastLong + 0.00050) || -73.03569,
            }}>
            <View>
              <Text style={{color: '#000'}}>
                { this.state.lastLong } / { this.state.lastLat }
              </Text>
            </View>
          </MapView.Marker>
        </MapView>
      </View>
    );
  }

Add the StyleSheet.absoluteFillObject for your map in order to render it properly using the whole width and height of your device.

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

So for your onPress() function you could do something similar to the onRegionChange(), that's to get the actual coordinates and to set them:

  onMapPress(e) {
    let region = {
      latitude:       e.nativeEvent.coordinate.latitude,
      longitude:      e.nativeEvent.coordinate.longitude,
      latitudeDelta:  0.00922*1.5,
      longitudeDelta: 0.00421*1.5
    }
    this.onRegionChange(region, region.latitude, region.longitude);
  }

Check the full code on expo.io (although react-native-maps isn't installed)

Fransiscafransisco answered 3/4, 2017 at 15:1 Comment(8)
Thnaks For your response , How can I get Current Location I Followed Your code But not show CurrentlocationKm
And one more Thing When i was click particular location It's full Zoom ,just i want show the location no need zoom how can i remove it Zooming alsoKm
You could set the zoomEnabled props to false, check here to see all the options available.Temperamental
No Actually I used Property gave true it's more ZoomEnabledKm
watchPositionImplAsync in LocationModule.java: 298, anyone??Apotropaic
Could you create a new question with the full stacktrace and error?Temperamental
What are the magic numbers 0.00922, 0.00421, and 1.5? And magic numbers 0.00050, -36.82339, and -73.03569?Clinic
is it calling when i move on i mean change location every second or time?Rapier
B
5

I suggest you to read this official documentation about geolocalisation: https://facebook.github.io/react-native/docs/geolocation.html

Then, with the current location, you can put that information into your state:

navigator.geolocation.getCurrentPosition((position) => {
    this.setState({position: {longitude: position.longitude, latitude: position.latitude}});
}, (error) => {
    alert(JSON.stringify(error))
}, {
    enableHighAccuracy: true,
    timeout: 20000,
    maximumAge: 1000
});

You will be able next, in your render method, to compose your final view with a marker:

render() {
  return (
    <MapView ...>
      <MapView.Marker
        coordinate={this.state.position}
        title="title"
        description="description"
      />
    </MapView>
  )
}
Bandicoot answered 3/4, 2017 at 7:28 Comment(2)
Thanks for your response...But, I want Current position lat and longKm
when i was click touch displayed lat long and show markerKm
J
1

Look for location permission using the following code:

try {
    const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
    )
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        alert("You can use the location")
    }
    else {
        alert("Location permission denied")
    }
}
catch (err) {
    console.warn(err)
}

Fetch the current location latitude and longitude using the following code:

this.watchID = navigator.geolocation.watchPosition((position) => {
    let region = {
        latitude:       position.coords.latitude,
        longitude:      position.coords.longitude,
        latitudeDelta:  0.00922*1.5,
        longitudeDelta: 0.00421*1.5
    }
}
Jephthah answered 29/10, 2018 at 6:29 Comment(4)
What are the magic numbers 0.00922, 0.00421, and 1.5? (Sebastian Palma's answer also has the magic numbers)Clinic
Hi, these are not the magic number. this totally depends upon your requirement. Here I have mentioned a random number. you can find this link helpful to undertand the concept of latitudeDelta and LogitudeDelta #36685872Jephthah
You can think like these values used to zoom in and zoom out the map. latitudeDelta is the difference between the latitude and similar for the longitude according to a map showing in the map. You can see a demo of this in above-mentioned linkJephthah
You can also visit google map api documentation for more infoJephthah

© 2022 - 2024 — McMap. All rights reserved.