想要通过React Native JS + Google API密钥获取当前位置

时间:2019-04-24 11:40:26

标签: react-native google-geocoder google-geolocation

我想在文本/警报中获取当前位置,以响应文本中的本机需求城市名称

这是我的代码:

getData(){

        Geocoder.init("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

        Geocoder.from(41.89, 12.49)
            .then(json => {
                var addressComponent = json.results[0].formatted_address;
          console.log(addressComponent);
          console.log(addressComponent)
         alert(addressComponent);
            })
          .catch(error => console.warn(error));
        }

3 个答案:

答案 0 :(得分:1)

使用此代码获取当前的纬度和经度:

navigator.geolocation.getCurrentPosition(
(position) => {
    console.log('lat',position.coords.latitude);
    console.log('lng',position.coords.longitude);
    //Your Code
    // ( DO fetch call to get address from lat and lng
    // https://maps.googleapis.com/maps/api/geocode/json?key= 
    <\API_KEY_HERE>&latlng="latitude","longitude"&sensor=true )
},
(error) => this.setState({ error: error.message }),
   { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);

答案 1 :(得分:1)

getData(){

<!DOCTYPE html>
<html>

<head>
  <title>Audio time set to zero</title>
</head>

<body>
  <audio id="myaudio" src="5 yr Plan - 140Bpm_Fm.mp3"></audio>
  <button onclick="settime()">play</button>
  <script type="text/javascript">
    function settime() {
      var audio = document.getElementById("myaudio");
      audio.currentTime = 0;
      audio.play();
      console.log(audio.currentTime);
      setInterval(function() {
        if (audio.currentTime > 60) {
          audio.pause();
        }
      }, 1000);
    }
  </script>
</body>

</html>

我想将其与当前位置纬度结合起来

答案 2 :(得分:0)

使用Geolocation API的完整示例。

正如我在评论中所说的;您无需使用Google API即可获取设备的当前坐标。您可以使用Geolocation API

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class FindMyLocationExample extends Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      error: null,
    };
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 10000, maximumAge: 1000 },
    );
  }

  render() {
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
      </View>
    );
  }
}