A function that adds different images to marker – React-native MapView

Viewed 83

With the use of this article https://medium.com/@clarkjohnson_85334/adding-fetched-markers-to-my-react-native-maps-app-5f068c7be14d, I have managed to integrate observations in my MapView.

 mapMarkers = () => {
    return this.state.items.map((item) => <Marker
        key={item.id}
        coordinate={{ latitude: item.geoLocation.latitude, longitude: item.geoLocation.longitude }}
        title={item.acceptedVernacularName}
        description={item.scientificName}
    >
    </Marker >)
}

However, I have not managed to make a function that adds different images to markers based on the type of bird. Is it even possible to make a function that can work with the Marker image={} prop which requries a string? My idea is that the image should be set local with require('../assets/xx') but based on either id or the name of the bird (acceptedVernacularName).

JSON file

1 Answers

Make a function like this to get custom icon based on your type

getIconFromType(type) {
        var icon = require("../image_path/");
        switch (type) {
            case "A": icon = require("../image_path/image_a.png");
                break
            case "B": icon = require("../image_path/image_b.png");
                break
            default: icon = require("../image_path/image_b.png");
                break
        }
        return icon
 }

then use this way to apply custom icon in marker based on your id

<Marker  ...other props>
 <Image source={this.getIconFromType(item.type)} resizeMode={'contain'} style={{ height: 30, width: 30 }} />
</Marker>
Related