在调用API之前如何获取用户的位置?

问题描述

我尝试制作的一个应用程序涉及从我的服务器中获取附近标记的部分。

我确定我的位置挂钩函数可以正常工作,但是在我进行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;

解决方法

解决方案是使用效果挂钩需要监视位置的变化, 所以

useEffect(() => {
 if (location) {
 couponBaseApi.request(location.latitude,location.longitude);
    }
  },[location]);

谢谢大家!

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...