Anonymous
React Native Maps не отображает маркеры на Android, хотя данные API извлекаются правильно
Сообщение
Anonymous » 26 окт 2025, 00:50
Я создаю приложение React Native для отображения маркеров местоположения на карте с помощью React-native-maps. Я использую поставщика Google Maps на Android.
Моя проблема в том, что карта загружается, но маркеры не видны, хотя я могу подтвердить, что мой вызов API успешен и возвращает действительный массив данных о местоположении.
MapsScreen.jsx:-
Код: Выделить всё
import React, { useState, useEffect, useRef, useMemo } from "react";
import {
View,
Text,
StyleSheet,
ActivityIndicator,
Alert,
SafeAreaView,
TouchableOpacity,
StatusBar,
Modal,
} from "react-native";
import MapView, { Marker, Callout, PROVIDER_GOOGLE } from "react-native-maps";
import { useRoute, useNavigation } from "@react-navigation/native";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import { fetchMaps } from "../services/maps";
const StatusIndicator = ({ text }) => (
{text}
);
const isValidCoord = (lat, lng) =>
Number.isFinite(lat) &&
Number.isFinite(lng) &&
Math.abs(lat) {
const getLocations = async () => {
if (!userId) {
setError("User ID not found. Cannot fetch map data.");
setIsLoading(false);
return;
}
try {
setIsLoading(true);
setError(null);
const data = await fetchMaps(userId);
const formattedData = Array.isArray(data)
? data
.map((point) => {
const lat = Number(point.latitude);
const lng = Number(point.longitude);
return {
...point,
latitude: Number.isFinite(lat) ? lat : NaN,
longitude: Number.isFinite(lng) ? lng : NaN,
pleasantness:
point.pleasantness != null ? Number(point.pleasantness) : null,
eventfulness:
point.eventfulness != null ? Number(point.eventfulness) : null,
annoyance:
point.annoyance != null ? Number(point.annoyance) : null,
};
})
.filter((p) => isValidCoord(p.latitude, p.longitude))
: [];
console.log("Points to plot:", formattedData.length, formattedData.slice(0, 3));
setPoints(formattedData);
} catch (err) {
console.error("Failed to fetch map data:", err);
setError(err.message || "Could not load map data.");
Alert.alert("Error", err.message || "Could not load map data.");
} finally {
setIsLoading(false);
}
};
getLocations();
}, [userId]);
const coords = useMemo(
() => points.map((p) => ({ latitude: p.latitude, longitude: p.longitude })),
[points]
);
useEffect(() => {
if (!mapReady || !mapRef.current || coords.length === 0) return;
if (coords.length === 1) {
const p = coords[0];
mapRef.current.animateToRegion(
{
latitude: p.latitude,
longitude: p.longitude,
latitudeDelta: 0.02,
longitudeDelta: 0.02,
},
600
);
} else {
mapRef.current.fitToCoordinates(coords, {
edgePadding: { top: 100, right: 100, bottom: 100, left: 100 },
animated: true,
});
}
}, [mapReady, coords]);
if (isLoading) {
return ;
}
if (error) {
return ;
}
if (points.length === 0) {
return ;
}
return (
navigation.goBack()} style={{ padding: 5 }}>
Analysis Map
setShowInfo(true)} style={{ padding: 5 }}>
About The Map
This map shows the locations of all saved sound analyses. Tap on any pin to see the details of that specific analysis.
setShowInfo(false)}>
Got It
setMapReady(true)}
onLayout={() => setMapReady(true)}
>
{points.map((point, index) => (
Analysis Details
Pleasantness:{" "}
{typeof point.pleasantness === "number"
? point.pleasantness.toFixed(2)
: "N/A"}
Eventfulness:{" "}
{typeof point.eventfulness === "number"
? point.eventfulness.toFixed(2)
: "N/A"}
Annoyance:{" "}
{typeof point.annoyance === "number"
? point.annoyance.toFixed(2)
: "N/A"}
))}
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#181d23",
},
map: {
flex: 1,
},
header: {
width: "100%",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingVertical: 14,
paddingHorizontal: 10,
paddingTop: 30,
backgroundColor: "#181d23",
},
headerTitle: {
fontSize: 20,
color: "#fff",
fontWeight: "bold",
},
statusContainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#181d23",
},
statusText: {
marginTop: 20,
fontSize: 16,
color: "#B6BAC5",
},
calloutView: {
padding: 10,
width: 200,
},
calloutTitle: {
fontWeight: "bold",
fontSize: 16,
marginBottom: 5,
},
overlay: {
flex: 1,
backgroundColor: "rgba(0,0,0,0.7)",
justifyContent: "center",
alignItems: "center",
},
infoModalBox: {
backgroundColor: "#2D2E32",
padding: 25,
borderRadius: 15,
width: "85%",
borderWidth: 1,
borderColor: "rgba(255, 255, 255, 0.1)",
},
infoTitle: {
color: "#FFFFFF",
fontSize: 18,
fontWeight: "bold",
textAlign: "center",
marginBottom: 15,
},
infoText: {
color: "#E0E0E0",
fontSize: 15,
lineHeight: 22,
marginBottom: 25,
},
closeBtn: {
backgroundColor: "#27F0C9",
paddingVertical: 12,
paddingHorizontal: 30,
alignSelf: "center",
borderRadius: 8,
},
closeText: {
color: "#181d23",
fontWeight: "bold",
fontSize: 16,
},
});
export default MapsAnalysis;
Подробнее здесь:
https://stackoverflow.com/questions/797 ... -is-fetche
1761429050
Anonymous
Я создаю приложение React Native для отображения маркеров местоположения на карте с помощью React-native-maps. Я использую поставщика Google Maps на Android. Моя проблема в том, что карта загружается, но маркеры не видны, хотя я могу подтвердить, что мой вызов API успешен и возвращает действительный массив данных о местоположении. MapsScreen.jsx:- [code]import React, { useState, useEffect, useRef, useMemo } from "react"; import { View, Text, StyleSheet, ActivityIndicator, Alert, SafeAreaView, TouchableOpacity, StatusBar, Modal, } from "react-native"; import MapView, { Marker, Callout, PROVIDER_GOOGLE } from "react-native-maps"; import { useRoute, useNavigation } from "@react-navigation/native"; import Icon from "react-native-vector-icons/MaterialCommunityIcons"; import { fetchMaps } from "../services/maps"; const StatusIndicator = ({ text }) => ( {text} ); const isValidCoord = (lat, lng) => Number.isFinite(lat) && Number.isFinite(lng) && Math.abs(lat) { const getLocations = async () => { if (!userId) { setError("User ID not found. Cannot fetch map data."); setIsLoading(false); return; } try { setIsLoading(true); setError(null); const data = await fetchMaps(userId); const formattedData = Array.isArray(data) ? data .map((point) => { const lat = Number(point.latitude); const lng = Number(point.longitude); return { ...point, latitude: Number.isFinite(lat) ? lat : NaN, longitude: Number.isFinite(lng) ? lng : NaN, pleasantness: point.pleasantness != null ? Number(point.pleasantness) : null, eventfulness: point.eventfulness != null ? Number(point.eventfulness) : null, annoyance: point.annoyance != null ? Number(point.annoyance) : null, }; }) .filter((p) => isValidCoord(p.latitude, p.longitude)) : []; console.log("Points to plot:", formattedData.length, formattedData.slice(0, 3)); setPoints(formattedData); } catch (err) { console.error("Failed to fetch map data:", err); setError(err.message || "Could not load map data."); Alert.alert("Error", err.message || "Could not load map data."); } finally { setIsLoading(false); } }; getLocations(); }, [userId]); const coords = useMemo( () => points.map((p) => ({ latitude: p.latitude, longitude: p.longitude })), [points] ); useEffect(() => { if (!mapReady || !mapRef.current || coords.length === 0) return; if (coords.length === 1) { const p = coords[0]; mapRef.current.animateToRegion( { latitude: p.latitude, longitude: p.longitude, latitudeDelta: 0.02, longitudeDelta: 0.02, }, 600 ); } else { mapRef.current.fitToCoordinates(coords, { edgePadding: { top: 100, right: 100, bottom: 100, left: 100 }, animated: true, }); } }, [mapReady, coords]); if (isLoading) { return ; } if (error) { return ; } if (points.length === 0) { return ; } return ( navigation.goBack()} style={{ padding: 5 }}> Analysis Map setShowInfo(true)} style={{ padding: 5 }}> About The Map This map shows the locations of all saved sound analyses. Tap on any pin to see the details of that specific analysis. setShowInfo(false)}> Got It setMapReady(true)} onLayout={() => setMapReady(true)} > {points.map((point, index) => ( Analysis Details Pleasantness:{" "} {typeof point.pleasantness === "number" ? point.pleasantness.toFixed(2) : "N/A"} Eventfulness:{" "} {typeof point.eventfulness === "number" ? point.eventfulness.toFixed(2) : "N/A"} Annoyance:{" "} {typeof point.annoyance === "number" ? point.annoyance.toFixed(2) : "N/A"} ))} ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#181d23", }, map: { flex: 1, }, header: { width: "100%", flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingVertical: 14, paddingHorizontal: 10, paddingTop: 30, backgroundColor: "#181d23", }, headerTitle: { fontSize: 20, color: "#fff", fontWeight: "bold", }, statusContainer: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "#181d23", }, statusText: { marginTop: 20, fontSize: 16, color: "#B6BAC5", }, calloutView: { padding: 10, width: 200, }, calloutTitle: { fontWeight: "bold", fontSize: 16, marginBottom: 5, }, overlay: { flex: 1, backgroundColor: "rgba(0,0,0,0.7)", justifyContent: "center", alignItems: "center", }, infoModalBox: { backgroundColor: "#2D2E32", padding: 25, borderRadius: 15, width: "85%", borderWidth: 1, borderColor: "rgba(255, 255, 255, 0.1)", }, infoTitle: { color: "#FFFFFF", fontSize: 18, fontWeight: "bold", textAlign: "center", marginBottom: 15, }, infoText: { color: "#E0E0E0", fontSize: 15, lineHeight: 22, marginBottom: 25, }, closeBtn: { backgroundColor: "#27F0C9", paddingVertical: 12, paddingHorizontal: 30, alignSelf: "center", borderRadius: 8, }, closeText: { color: "#181d23", fontWeight: "bold", fontSize: 16, }, }); export default MapsAnalysis; [/code] [img]https://i.sstatic.net/TF1W4ZJj.png[/img] [img]https://i.sstatic.net/tWYwAyf0.png[/img] [img]https://i.sstatic.net/EDo5QEEZ.png[/img] [img]https://i.sstatic.net/gYmF28EI.png[/img] [img]https://i.sstatic.net/pzqGvlBf.png[/img] Подробнее здесь: [url]https://stackoverflow.com/questions/79796123/react-native-maps-not-showing-markers-on-android-even-though-api-data-is-fetche[/url]