我有一个 Geolocation.js,它获取地理位置并将其记录到控制台。这是导入到 index.js 文件中,需要使用那些 lat
和 lng
记录的值,以替换 ll
中的当前硬编码值其中:
import * as fsAPI from "../data/API_credentials";
import {userGeo} from "../component/Geolocation"
class Helper {
static baseURL() {
return "https://api.foursquare.com/v2";
}
// Client ID, client secret, and version stored in credentials file
static auth(){
const keys = {
client_id: `${fsAPI.client_id}`,
client_secret: `${fsAPI.client_secret}`,
v: `${fsAPI.client_version}`,
// Trying to get data from {userGeo}
// ll: `${userGeo.pos.lat}` + "," + `${userGeo.pos.lng}` //cannot read 'pos' of undefined.
// Line below works
ll: "36.04,-86.74"
}
return Object.keys(keys).map(key => `${key}=${keys[key]}`)
.join("&");
}
我导入的代码为 userGeo
进入上面的代码如下,那是我的错误。我如何重构它以允许我获取 lat lng
在ll
多于? userGeo.pos.lat
例如。
你可以在 // ll: `${userGeo.pos.lat}` + "," + `${userGeo.pos.lng}`
中看到我失败的尝试, 抛出 cannot read 'pos' of undefined.
// Geolocation of user to be used for search query Foursqaure call url
export const userGeo = navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log(pos) // works
console.log("Lat: " + pos.lat) // works
});
非常感谢! 本
最佳答案
navigator.geolocation.getCurrentPosition
是异步的。它接受回调作为第一个参数,将在检索位置后调用。我的建议是在 auth
函数中 promise 并使用它:
// Geolocation.js
export const getUserGeo = function (options) {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject, options);
});
}
// Helper.js
import { getUserGeo } from "../component/Geolocation";
class Helper {
static baseURL() {
return "https://api.foursquare.com/v2";
}
static auth(){
return getUserGeo()
.then(position => {
const keys = {
client_id: `${fsAPI.client_id}`,
client_secret: `${fsAPI.client_secret}`,
v: `${fsAPI.client_version}`,
ll: `${position.coords.latitude}` + "," + `${position.coords. longitude}`
};
return Object.keys(keys).map(key => `${key}=${keys[key]}`).join("&");
});
}
请记住,不是 auth()
方法是异步的,它返回一个 Promise
,它将使用 Object.keys(keys ).map(key =>
${key}=${keys[key]}).join("&")
关于javascript - 如何在 React 中将地理位置经纬度从一个函数传递到另一个函数的 `ll` 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53159718/