如何在React中将地理位置定位函数从函数传递到另一个人的`ll`属性?

时间:2018-11-05 17:56:41

标签: javascript reactjs syntax geolocation

我有一个Geolocation.js,它获取地理位置并将其记录到控制台。它将导入到index.js文件中,需要使用已记录的latlng值来替换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
});

非常感谢! 本

1 个答案:

答案 0 :(得分:1)

navigator.geolocation.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("&"); 
               });
}

请记住,不是auth()方法是异步的,它会返回Promise,该值将以Object.keys(keys).map(key => $ {key} = $ {keys [key]的值进行解析} ).join("&")