'How To Loop Through Array Inside a MapView object
I have a MapView that I want to add Markers to. I can successfully add Markers individually but I want to loop through an array of coordinates and add a marker for each location in the array. Whenever trying to run this code, I get an "Unexpected Token" error where the for loop begins. I have read suggestions about using the .map function on the array but that does not seem to work for me either. Any help would be highly appreciated.
const ViewNearbyScreen = ({
navigation, route
}) => {
const points = [
{
name: "Wendys",
lat: 37.4319983,
lng: -122.094,
},
{
name: "Taco Bell",
lat: 37.4419983,
lng: -122.104,
},
{
name: "Whataburger",
lat: 37.4519983,
lng: -122.114,
},
];
return (
<MapView
provider={PROVIDER_GOOGLE}
style={{flex: 1}}
region={{
latitude: 37.4219983,
longitude: -122.084,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}}
ref={mapRef}
showsUserLocation>
{for(let i = 0; i < 3; i++) {
<Marker
coordinate={{
latitude: points[{i}].lat,
longitude: points[{i}].lng,
}}
title={points[{i}].name}
/>
}}
</MapView>
)
};
Solution 1:[1]
You can use the Array Map method to loop through the array elements.
points.map(item => { // each point in points array
return (
<Marker
coordinate={{
latitude: item.lat,
longitude: item.lng,
}}
title={item.name}
/>
)
})
The reason the map method wasn't working for you might be that you forgot to return your jsx.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nithinpp |
