【发布时间】:2020-10-16 03:58:00
【问题描述】:
我正在尝试制作的应用涉及从我的服务器获取附近标记的部分。
我确信我的位置挂钩函数可以工作,但是,在我调用 API 以获取该位置附近的标记之前,它还没有完成。
这让我困惑了好几个小时,所以任何帮助都将不胜感激!
import React, { useEffect, useState } from "react";
import MapView, { PROVIDER_GOOGLE, Marker } from "react-native-maps";
import { StyleSheet, View, Dimensions, Platform } from "react-native";
import useLocation from "../hooks/useLocation";
import useApi from "../hooks/useApi";
import couponsInArea from "../api/couponsInArea";
const customData = require("../assets/map_styles/day_map.json");
function MapScreen(props) {
//Here is the location hook
var location = useLocation();
const couponBaseApi = useApi(couponsInArea.getCouponBases);
//Here is the API call that needs the location
useEffect(() => {
if (location) {
couponBaseApi.request(location.latitude, location.longitude);
}
}, []);
return (
<View style={styles.container}>
<MapView
followUserLocation={true}
zoomEnabled={true}
showsUserLocation={true}
style={styles.mapStyle}
provider={PROVIDER_GOOGLE}
customMapStyle={customData}
initialRegion={{
latitude: location.latitude,
longitude: location.longitude,
latitudeDelta: 0.0158,
longitudeDelta: 0.007,
}}
>
{couponBaseApi.data.couponBases.map((report) => (
<Marker
key={report.couponBaseID}
coordinate={{
latitude: report.latitude,
longitude: report.longitude,
}}
></Marker>
))}
</MapView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
mapStyle: {
width: Dimensions.get("window").width,
height: Dimensions.get("window").height,
},
});
export default MapScreen;
【问题讨论】:
-
您的
useLocation函数看起来如何?它是否在进行异步调用以获取位置?如果是这样,您需要使 MapScreen 函数异步并将 await 放在useLocation之前,例如var location = await useLocation。
标签: react-native api location react-native-maps