0
votes

I have google map where I need marker updated dynamically from custom API with GPS latitude and longitude coordinates. I have written componentWillMount() function where I fetch the date but the data is not passed for some reason to the current state of the longitude/latitude. I am new to the react native, I have build two fully functional applications but I am still struggling with states.

I have tried a lot of hard coded examples which all worked for me but response from API and setting it as a pin on the map is not.

class MarkerTypes extends React.Component {
          constructor(props) {
            super(props);

             this.state = {

               isLoading: true,
               jsondata: [],
               error: null,

Second part of the code where I've done functions. This is what API returns

{"lat": "45.23846817", "lon": "19.80212021"}
fetchData() {
    fetch('API')
      .then((response) => response.json())
      .then(data =>

        this.setState({
        jsondata: data,
        isLoading: false,
      })
    )
  }

  componentDidMount() {
    this.fetchData();
    console.log(this.jsondata)
  }

Third part where I want my marker pointed out and updated after the change has been made in the API location vise. My console log of the response seems fine but I can't get the values passed for the marker later, keeps saying undefined.

<MapView.Marker
  testID="API GPS"
  coordinate={this.state.jsondata}
  image={this.Marker}
/>

Can't seem to find the solution online. All the solutions related to my problems seems to be using geo location or hard coding the parts of the code which doesn't help me at all with my issue here.

1
improved code formattingChrisG

1 Answers

0
votes

Marker takes coordinate as LatLng which means you need to pass coordinator value as

{
   latitude:value, 
   longitude:value
}

in your case it is passed as {lat:value, lon:value}

Once you get the response from api, store data in object

this.setState({
    jsondata: {latitude:data.lat, longitude:data.lon},
    isLoading: false,
})