简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM