marry
marry

Reputation: 51

React native Markers fetched from API wont show on map and const markers is undefined

I am making my first mobile application in React native. Im trying to render markers that have fetched longitude and latitude from a Api. To test this I have used an Api that has a random address in the Netherlands. I have written code to fetch this Api and map through the keys to render the markers, only they won't show on my map. This is the code I wrote for the fetching for the Api and the mapping of the keys to get markers:

import React, {useState, useEffect} from 'react';


import { Marker }from 'react-native-maps'
import { View } from 'react-native';

function SupermarketList() {
    const [data, setData] = useState([]);

    useEffect( () => {
    fetch('http://api.postcodedata.nl/v1/postcode/?postcode=1211EP&streetnumber=60&ref=domeinnaam.nl&type=json', {
        headers: {
            'Cache-Control': 'no-cache',
        },
    })
    .then(response => response.json())
    .then(results => {
        setData(results.details);
        console.log(results);
    })
    .catch(error => console.error(error));
}, []);

const markers = data.map((supermarket, index) => {
    const lon = supermarket.lon
    const lat = supermarket.lat
    console.log(markers)
    return (
        <Marker key={index} coordinate={{ lat, lon}}/>
    )
})

return (
    <View>
        {markers}
    </View>
)
}

export default SupermarketList
    

Like I said, the markers won't show up on the map. I have put some console.logs to see where the problem is because I'm getting no errors. console.log(results) works and gives me back api data, same thing for console.log(supermarket). What doesn't work is console.log(markers). This gives me back "undefined". I have no Idea why!

Upvotes: 0

Views: 847

Answers (2)

newbie
newbie

Reputation: 21

You need to change from

<Marker key={index} coordinate={{ lat, lon}}/>

to

<Marker key={index} coordinate={{latitude: lat, longitude: lon}}/>

Upvotes: 1

Dorian Gjini
Dorian Gjini

Reputation: 1

If everything comes okay from API, try to pass to coordinate prop, this interface LatLng { latitude: number; longitude: number; }

Upvotes: 0

Related Questions