Javascript 如何将地理定位lat lng从一个功能传递到另一个功能';你的财产在哪里?
我有一个Geolocation.js,它获取地理位置并将其记录到控制台。这被导入到index.js文件中,需要使用记录的Javascript 如何将地理定位lat lng从一个功能传递到另一个功能';你的财产在哪里?,javascript,reactjs,syntax,geolocation,Javascript,Reactjs,Syntax,Geolocation,我有一个Geolocation.js,它获取地理位置并将其记录到控制台。这被导入到index.js文件中,需要使用记录的lat和lng值来替换此文件的ll中的当前硬编码值: import * as fsAPI from "../data/API_credentials"; import {userGeo} from "../component/Geolocation" class Helper { static baseURL() { return "h
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
导入上述代码的代码,这是我的错误。我如何重构它,以便能够获取上面ll
中的lat lng
<例如,code>userGeo.pos.lat
您可以在上面的/ll:`{userGeo.pos.lat}`+'、“+`${userGeo.pos.lng}`
中看到我失败的尝试,它抛出无法读取未定义的'pos'。
// 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
});
非常感谢!
Ben导航器。地理位置。getCurrentPosition是异步的。它接受回调作为第一个参数,该参数将在检索位置后调用。我建议您在
auth
函数中使用它:
// 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("&");
});
}
请记住,not
auth()
方法是异步的,它返回一个Promise
,该值将用Object.keys(keys).map(key=>
${key}=${keys[key]})的值来解析。join(&”)
我尝试了这个方法,API url的ll
是[Object 20Promise]
,你有什么建议吗如果我console.log(position.coords.latitude)
就在return Object.keys…
行之前,它会将lat
记录到控制台。在使用auth()
方法的地方共享代码。似乎您并不是在等待auth()
返回的承诺来解决问题。谢谢您-我在以代码格式粘贴它时遇到了困难-我使用了您最初完全共享的内容`静态auth(){return getUserGeo()。然后(position=>{const key={client\u id:${fsAPI.client\u id}
,client\u secret:${fsAPI.client\u secret}
,v:${fsAPI.client\u version}
,ll:${position coords.纬度}+,“+${position coords.coords.longitude}
;console.log(position.coords.latitude)return Object.keys(keys).map(key=>${key}=${keys[key]}
).join(“&”);}`我在询问调用Helper.auth()
的代码段