Hector4888
Hector4888

Reputation: 569

React -Native "Value for longitude cannot be cast from String to Double"

I am using react-native-maps and I get lat and long using this code:

callLocation(that) {
  navigator.geolocation.getCurrentPosition(
    position => {
      const currentLongitude = JSON.stringify(position.coords.longitude);
      const currentLatitude = JSON.stringify(position.coords.latitude);
      that.setState({ currentLongitude: currentLongitude });
      that.setState({ currentLatitude: currentLatitude });
    },
    error => alert(error.message),
    { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
  );
  that.watchID = navigator.geolocation.watchPosition(position => {
    console.log(position);
    const currentLongitude = JSON.stringify(position.coords.longitude);
    const currentLatitude = JSON.stringify(position.coords.latitude);
    that.setState({ currentLongitude: currentLongitude });
    that.setState({ currentLatitude: currentLatitude });
  });
}

And this is my mapview code:

<MapView
  style={styles.map}
  initialRegion={{
    latitude: this.state.currentLatitude,
    longitude: this.state.currentLongitude,
    latitudeDelta: 0.0922,
    longitudeDelta: 0.0421
  }}
/>

When I paste this lat and long in my code I got following error:

Upvotes: 2

Views: 7112

Answers (4)

Mustapha GHLISSI
Mustapha GHLISSI

Reputation: 1710

Nothing to do easier than parsing the coords position like this:

{
   latitude: parseFloat(myObj.latitude),
   longitude: parseFloat(myObj.longitude)
}

Upvotes: 5

Qusain
Qusain

Reputation: 1

const currentLongitude = position.coords.longitude;
const currentLatitude = position.coords.latitude;

my issue has solved by using the code above

Upvotes: 0

fazeel haider
fazeel haider

Reputation: 5

This issue generates when your lat long is in String convert it into float.

Upvotes: 0

Andrew
Andrew

Reputation: 28539

Your issue is that you are making the coordinate a string and it is required to be a double.

You shouldn’t be using JSON.stringify

const currentLongitude = JSON.stringify(position.coords.longitude);
const currentLatitude = JSON.stringify(position.coords.latitude);

You should do this instead

const currentLongitude = position.coords.longitude;
const currentLatitude = position.coords.latitude;

Upvotes: 3

Related Questions