javascript - 如何从数组中仅获取经度和纬度

标签 javascript react-native

菜鸟问题,但找不到好的答案, 我试图只在不同的字符串中获取经度和纬度。目前它有效但它记录了这个:

Object {
  "coords": Object {
    "accuracy": 5,
    "altitude": 0,
    "altitudeAccuracy": -1,
    "heading": -1,
    "latitude": 37.785834,
    "longitude": -122.406417,
    "speed": -1,
  },
  "timestamp": 1577094980806.544,

这是代码:

import styled from "styled-components";
import * as Permissions from "expo-permissions";
import * as Location from "expo-location";

export default class GetLocation extends React.Component {
  state = {
    location: {},
    errorMessage: ""
  };

  constructor(props) {
    super(props);
    this.state = {
      longitude: [],
      latitude: []
    };
  }

  componentDidMount() {
    this._getLocation();
  }

  _getLocation = async () => {
    const { status } = await Permissions.askAsync(Permissions.LOCATION);

    if (status !== "granted") {
      console.log("PERMISSION NOT GRANTED!");

      this.setState({
        errorMessage: "PERMISSION NOT GRANTED"
      });
    }
    const location = await Location.getCurrentPositionAsync();
    this.setState({
      location
    });
    return location.JSON;
  };

  render() {
    console.log(this.state.location);

    return (
      <View>
        <Text>{JSON.stringify(this.state.location)}</Text>
      </View>
    );
  }
}

const View = styled.View``;
const Text = styled.Text`
  font-size: 12px;
  color: black;
`;

我要导出经度和纬度。我知道代码有点乱。非常感谢任何建议。

最佳答案

不需要解析JSON,已经是对象了:

 const location = await Location.getCurrentPositionAsync();
    this.setState({
      location : {
        lat: location.coords.latitude,
        lon: location.coords.longitude
      }
    });

渲染:

 <View>
    <Text>{this.state.location.lat} {this.state.location.lon} </Text>
  </View>

关于javascript - 如何从数组中仅获取经度和纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59453303/

相关文章:

javascript - 用于测试元素是否包含在有限集中的位掩码解决方案?

javascript - WebKit 动画已启动,但卡住在第一帧(仅限 Safari)

react-native - 导航器弹出时如何更新组件?

javascript - jQuery 可从一个 div 排序到另一个

javascript - ajax 请求中的 formdata 返回 Uncaught TypeError : Illegal invocation error

javascript - 通过字符串路径设置嵌套对象属性

android - 在 React Native 的胜利图表中找不到方法 google() 错误

react-native - React Native - 什么时候会调用 "componentWillUnmount"?

ios - 人们如何使用 React Native 处理 iOS 中的 "recent app"箭头?

javascript - react native 动态渲染