Load offline maps from mbtiles file and render it in react native android app

475 views Asked by At

I need to display an offline map in a mobile application for Android on React Native. I have a generated mbtiles file. Tried different libraries. Tell me what I'm doing wrong? Which library is better to use? If it is possible give refer to code examples or similar implementations.

my code:

import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import MapView, { Marker } from 'react-native-maps';
import RNFS from 'react-native-fs';

const MapScreen = () => {
  const [mapReady, setMapReady] = useState(false);
  const [offlineMapUri, setOfflineMapUri] = useState(null);

  //change **.****** to youre test data
  const YOUR_INITIAL_LATITUDE = **.******;
  const YOUR_INITIAL_LONGITUDE = **.******;
  const YOUR_INITIAL_LATITUDE_DELTA = *.**;
  const YOUR_INITIAL_LONGITUDE_DELTA = *.**;
  const YOUR_MARKER_LATITUDE = **.******;
  const YOUR_MARKER_LONGITUDE = **.******;
  
  useEffect(() => {
    loadOfflineMap();
  }, []);

  const loadOfflineMap = async () => {
    
    const offlineMapPath = `${RNFS.ExternalStorageDirectoryPath}/Android/data/com.android.slk3/files/my_map.mbtiles`;

    try {
      
      const mapFileExists = await RNFS.exists(offlineMapPath);

      if (mapFileExists) {
        setOfflineMapUri(`file://${offlineMapPath}`);
      } else {
        console.log('file not found.');
      }
    } catch (error) {
      console.error('Error loading map:', error);
    }
  };

  const onMapLayout = () => {
    setMapReady(true);
  };

  return (
    <View style={{ flex: 1 }}>
      {mapReady && offlineMapUri ? (
        <MapView
          style={{ flex: 1 }}
          initialRegion={{
            latitude: YOUR_INITIAL_LATITUDE,
            longitude: YOUR_INITIAL_LONGITUDE,
            latitudeDelta: YOUR_INITIAL_LATITUDE_DELTA,
            longitudeDelta: YOUR_INITIAL_LONGITUDE_DELTA,
          }}
          onLayout={onMapLayout}
        >
          <Marker
            coordinate={{
              latitude: YOUR_MARKER_LATITUDE,
              longitude: YOUR_MARKER_LONGITUDE,
            }}
            title="Your Marker"
            description="This is your marker"
          />
        </MapView>
      ) : (
        <View>
          <Text>mapReady: {mapReady}</Text>
          <Text>offlineMapUri: {offlineMapUri}</Text>
        </View>
      )}
    </View>
  );
};

export default MapScreen;

I have tried different libs, for example mapbox, maplibre, react native maps, google maps. But I still couldn't read the file and show the map.

0

There are 0 answers