Aniket Biswas
Aniket Biswas

Reputation: 1

React Native Maps is not displaying my location and markers every time I render the map

I am using React Native v0.76.1. When I open the app and navigate to the map page, my location and the markers appear correctly. However, after navigating back and returning to the same page, my location and markers do not display. And the location indicator is not showing on my phone as well when gps location is used. But my location is on in my device.

Sample Code:-

import { View, Text, StyleSheet } from 'react-native';
import React from 'react';
import MapView, { Marker } from 'react-native-maps';
import { responsiveHeight } from 'react-native-responsive-dimensions';

const NewStoreLocator = () => {
  const storeMarkers = [
    {
      latitude: 37.78925,
      longitude: -122.4324,
      title: 'Pink Paws Store 1',
      description: 'Your favorite store for pink paws in town.',
    },
    {
      latitude: 37.79025,
      longitude: -122.4334,
      title: 'Pink Paws Store 2',
      description: 'Another branch with amazing pink paws.',
    },
    {
      latitude: 37.78725,
      longitude: -122.4304,
      title: 'Pink Paws Store 3',
      description: "Don't miss out on our latest collection.",
    },
    {
      latitude: 37.78850,
      longitude: -122.4340,
      title: 'Pink Paws Store 4',
      description: 'Visit us for the best pink paws in the area!',
    },
    {
      latitude: 37.78625,
      longitude: -122.4315,
      title: 'Pink Paws Store 5',
      description: 'Exclusive offers at this location.',
    },
  ];

  return (
    <MapView
      initialRegion={{
        latitude: 37.78825,
        longitude: -122.4324,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
      }}
      showsUserLocation={true}
      style={styles.map}
    >
      {storeMarkers.map((marker, index) => (
        <Marker
          key={`${marker.latitude}-${marker.longitude}-${index}`}
          coordinate={{ latitude: marker.latitude, longitude: marker.longitude }}
          title={marker.title}
          description={marker.description}
        />
      ))}
    </MapView>
  );
};

const styles = StyleSheet.create({
  map: {
    height: responsiveHeight(50),
    width: '100%',
    marginBottom: 10,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 10,
  },
});

export default NewStoreLocator;

I have changed the api key as well but still the same. I just want to render my location (or user's current location) and few markers.

Upvotes: 0

Views: 184

Answers (1)

torodebout
torodebout

Reputation: 1

Add a prop key to MapView like this:

<MapView
      key={Platform.OS === "android" ? `${Key}` : "map"}
...
/>

And define a state:

const [key, setKey] = React.useState(0);

Then add useEffect:

useEffect(() => {
    if (Platform.OS === "android") {
      setKey((prev) => prev + 1);
      setIsMapReady(false);
    }
  }, [storeMarkers]);

Upvotes: 0

Related Questions