簡體   English   中英

如何從數組中只獲取經度和緯度

[英]How to get only longitude and latitude from array

菜鳥問題但找不到好的答案,我試圖只在不同的字符串中最好地獲得經度和緯度。 目前它可以工作,但它會記錄以下內容:

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;
`;

我想導出經度和緯度。 我知道代碼有點亂。 任何建議都非常感謝。

您是否嘗試過以這種方式訪問​​:

console.log(this.state.location.coords.latitude);

不需要解析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>

您可以使用destructuring來做到這一點,

嘗試這個:

 let locationObj = { "coords": { "accuracy": 5, "altitude": 0, "altitudeAccuracy": -1, "heading": -1, "latitude": 37.785834, "longitude": -122.406417, "speed": -1, }, "timestamp": 1577094980806.544, } const res = (({ latitude, longitude }) => ({ latitude, longitude }))(locationObj.coords); console.log(res);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM