Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple markers are not showing on map in react Native

i am trying to show multiple markers on map in but i the markers are not showing and there's no error so i am unable to solve it,so Basically i am trying to get the coordinates from the state and trying to show multiple markers.Since i am new to react Native i might be doing something stupidly wrong.

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import MapView from 'react-native-maps'


export default class App extends Component {
  render() {
    this.state = {
      markers: [{
        title: 'hi',
        coordinates: {
          latitude: 3.148561,
          longitude: 101.652778
        },
      },
      {
        title: 'hello',
        coordinates: {
          latitude: 3.149771,
          longitude: 101.655449
        },

      },
      {
        title: 'hey',
        coordinate: {
          latitude: 33.5336684,
          longitude: 131.3420892
        },

      },
      {
        title: 'heyThere',
        coordinate: {
          latitude: 24.8345714,
          longitude: 67.3589759
        }
      }
      ]
    }
    return (

      <MapView
        style={{ flex: 1 }}
        showsUserLocation={true}

      >
        {this.state.markers.map((marker, index) => (
          <MapView.Marker key={index}
            coordinate={marker.coordinates}
            title={marker.title}
          />
        ))}
      </MapView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
like image 345
theCoder Avatar asked Feb 26 '26 14:02

theCoder


1 Answers

Move

this.state = {
      markers: [{
        title: 'hi',
        coordinates: {
          latitude: 3.148561,
          longitude: 101.652778
        },
      },
    ...

to the constructor or just keep it in the class (Remove from the render function).

There are typos in markers array. Set the same key for all elements in the markers array (Currently you have coordinates and coordinate).

Also try to change the style of the MapView to { width: '100%', height: '100%' } if it doesn't render the MapView.

like image 128
Gev Avatar answered Feb 28 '26 06:02

Gev