javascriptreact-nativelatitude-longitudemapview

How to display Multiple markers in MapView With pincolor


I want to display on my map multiple markers for multiple latitude and longitude in MapView on React Native. I am getting the latitude and longitude by fetch Data from API. Now How Can I show In my React Native for All position in map using those Data.

my codes is:

useEffect(() => {
    devices?.map(async (id) => {

        await fetch(`https://www.schools.com/sc/api/${id}`, requestOptions)
            .then((response) => response.json())
            .then(function (response) {
             return setDataLoc([parseFloat(response.data?.latitude), parseFloat(response.data?.longitude)])
            })
            .catch(function (error) {
                console.log(error);
            });
    })

}, [])


const [curLoc, setCurLoc] = useState({
    latitude: 5.055252,
    longitude: 115.9456243,
    latitudeDelta: 0.004757,
    longitudeDelta: 0.006866,

})

return (
    <View style={styles.container}>
        <MapView style={styles.map}
            initialRegion={curLoc}>
            {devices?.map((val) => {
                return (<Marker
                    coordinate={val.dataLoc}
                    pinColor="black">
                </Marker>)
            })}
        </MapView>
    </View>
);

Now i have more latitude and longitude to display. I get my data after fetch something's like,

Output:

[5.7689,110.5677]
[5.2345,111.5623]
[5.6652,112.7890]

After execute this I can't able to view any marker on my Map.

So I want to display those 3 latitude and longitude location in my Map View.

how can I do all position using marker I can display in Maps.


Solution

  • I think you error comes from the wrong type you are giving in props to coordinate on the marker component, coordinate should be like that: { latitude : number , longitude : number }

    import MapView, { Marker } from 'react-native-maps';
        
        const [curLoc, setCurLoc] = useState({
          latitude: 5.055252,
          longitude: 115.9456243,
          latitudeDelta: 0.004757,
          longitudeDelta: 0.006866,
        })
    
        marketToDisplay = [
          {latitude: 5.7689, longitude: 110.5677},
          {latitude: 5.2345, longitude: 111.5623},
          {latitude: 5.6652, longitude: 112.7890},
        ]
      
        render() {
          return (
            <View style={styles.container}>
              <MapView style={styles.map} initialRegion={curLoc}>
                marketToDisplay.map((val, index) => {
                  <Marker
                    key={index}
                    coordinate={val}
                  />
                }
                <Marker coordinate={this.state.coordinate} />
              </MapView>
            </View>
          );
        }