我需要在 React Native 上的 Android 移动应用程序中显示离线地图。 我有一个生成的 mbtiles 文件。尝试了不同的库。 告诉我我做错了什么?使用哪个库更好?如果可能的话请参考代码示例或类似的实现。
我的代码:
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;
我尝试过不同的库,例如mapbox、maplibre、react Native 地图、google 地图。但我仍然无法读取文件并显示地图。