Value for latitude cannot be cast from String to Double in react-native

Viewed 4758

i have json

{
  "status": 200,
  "error": false,
  "driver": [
    {
      "id": "7",
      "name": "Kevin",
      "lat": "-6.2616031",
      "lon": "106.8424822"
    },
    {
      "id": "9",
      "name": "jhon",
      "lat": "-6.20032449",
      "lon": "106.6372306"
    },
}

here I am capturing or retrieving json data and displaying it on maps when i show i get an error problem which is:

Value for latitude cannot be cast from String to Double in react-native

where is the error ? this is my code

 componentDidMount() {
    fetch('https://example.com/myjson')
      .then(res => res.json())
      .then(data => {
        this.setState({ data: data.driver })
      })
      .catch(console.error)
   }

mapMarkers = () => {
        return this.state.data.map((driver) => <MapView.Marker
          key={driver.id}
          coordinate={{ "latitude": driver.lat, "longitude": driver.lon }}
          title={driver.name}
          description={driver.division}
        />)
      }

render() {
      return (
        <View style={styles.container}>
          <View style={{ flex: 2 }}>
            
            <MapView
            style={{ flex: 1, width: window.width }} //window pake Dimensions
            Region={{
                latitude: 106.8424822,
                longitude: -6.2616031,
                latitudeDelta: 70,
                longitudeDelta: 45
              }} >
            {this.mapMarkers()}
            </MapView>
          </View>
        </View>
      );
    }
3 Answers

The type of your latitude and longitude data in your JSON is string. You probably have to convert your latitude and longitude to double when passing them to Marker component's coordinate prop. So can you try this instead?

coordinate={{ "latitude": parseFloat(driver.lat), "longitude": parseFloat(driver.lon) }}

you must use lat or lng without Double quotation "" in state

for example:

"lat": -6.2616031,

not "lat": "-6.2616031",

The value passes to the latitude and longitude in mapview must not be in string format.

example:

<MapView style={{width:100%,height:"100%}} initialRegion={{ latitude : 11.610400, longitute: 76.083000, latitudeDelta:0.003, longitudeDelta:0.003 }} />

Related