Javascript 如何使用带有React Native的Expo location API获取当前位置?

Javascript 如何使用带有React Native的Expo location API获取当前位置?,javascript,react-native,Javascript,React Native,现在我正在制作一张地图,我们可以知道幼儿园的位置,但现在最早的地区是东京站。 当用户打开应用程序时,我想调整地图以获取当前位置,或者某个按钮不可用 按下。如何添加代码 下面是当前代码,按下按钮可以得到幼儿园的位置 import React from 'react'; import { StyleSheet, Text, View,TouchableOpacity } from 'react-native'; import MapView from 'react-native-maps'; imp

现在我正在制作一张地图,我们可以知道幼儿园的位置,但现在最早的地区是东京站。 当用户打开应用程序时,我想调整地图以获取当前位置,或者某个按钮不可用 按下。如何添加代码

下面是当前代码,按下按钮可以得到幼儿园的位置

import React from 'react';
import { StyleSheet, Text, View,TouchableOpacity } from 'react-native';
import MapView from 'react-native-maps';
import {point} from '@turf/helpers';
import destination from '@turf/destination';

export default class App extends React.Component {
    constructor(props) {
        super(props) 
        this.state = {
            elements: [],
            south:null,
            west:null,
            north:null,
            east:null,

        }
    }

        //地図の画面が変更されるたびにbboxを計算
        onRegionChangeComplete = (region) => {
        //111キロメートルから中心点から縦幅、横幅を計算
        const center = point([region.longitude, region.latitude])
        const verticalMeter = 111 * region.latitudeDelta / 2
        const horizontalMeter = 111 *region.longitudeDelta / 2
        //実際の距離を計算
        const options = {units: 'kilometers'}
        const south = destination(center,verticalMeter,180,options)
        const west = destination(center,horizontalMeter,-90,options)
        const north = destination(center,verticalMeter,0,options)
        const east = destination(center,horizontalMeter,90,options)
        //計算結果(GeoJson)からbboxを保存する
        this.setState({
            south:south.geometry.coordinates[1],
            west:west.geometry.coordinates[0],
            north:north.geometry.coordinates[1],
            east:east.geometry.coordinates[0],
        })
    }

        fetchToilet = async  () => {
            const south = this.state.south
            const west = this.state.west
            const north = this.state.north
            const east = this.state.east
            //テンプレートリテラルを使ってbboxを展開
            const body = `
            [out:json];
            (
                node
                [amenity=kindergarten]
                (${south},${west},${north},${east});

            );
            out;
            `

            //fetch関数に渡すoptionを指定
            const options = {
                method: 'POST',
                body: body
            }

            //fetch関数でOverpass APIのエントリポイントにアクセスし、取得したJSONを保存
            try {
                const response = await fetch('https://overpass-api.de/api/interpreter',options)
                const json = await response.json()
                this.setState({elements: json.elements})
            }catch (e) {
            console.log(e)
        
            }
}
    render() {
        return (
            <View style ={styles.container}>
            <MapView
            onRegionChangeComplete={this.onRegionChangeComplete}
                style={styles.mapView}
                initialRegion={{
                    latitude: 35.681236,
                    longitude: 139.767125,
                    latitudeDelta: 0.02, //小さくなるほどズーム
                    longitudeDelta: 0.02,
                }}>

                {
                    this.state.elements.map((element) =>{

                        let title= "保育園"
                        if (element.tags["name"] !==undefined) {
                            title = element.tags["name"]
                        }
                        return (<MapView.Marker
                            coordinate={{
                                latitude: element.lat,
                                longitude: element.lon,
                            }}
                            title={title}
                            key={"id_" + element.id}
                        />)
                    })

                }

                    </MapView>


            <View style ={styles.buttonContainer}>
            <TouchableOpacity
            onPress={() => this.fetchToilet()}
            style={styles.button}
            >
            <Text style={styles.buttonItem}>保育園取得</Text>
            </TouchableOpacity>
            </View>
            </View>
    
        );
    }
}

const styles = StyleSheet.create({

    container: {
      flex: 1,
      backgroundColor:'#fff',
      alignItems: 'center',
      justifyContent: 'flex-end',
      
    },
  
    mapView: {
      ...StyleSheet.absoluteFillObject,
    },
  
    

    buttonContainer: {
       flexDirection:'row',
       marginVertical:20,
       backgroundColor:'transparent',
       alignItems:'center',
    },
  
    button: {
        width:150,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:'rgba(255,235,255,0.7)',
        paddingHorizontal:18,
        paddingVertical:12,
        borderRadius:20,
    },

    buttonItem: {
        textAlign:'center',
    },


  });
从“React”导入React;
从“react native”导入{样式表、文本、视图、TouchableOpacity};
从“react native maps”导入MapView;
从'@turf/helpers'导入{point};
从“@turp/destination”导入目的地;
导出默认类App扩展React.Component{
建造师(道具){
超级(道具)
此.state={
要素:[],
南:空,
韦斯特:空,
北:空,
东:空,
}
}
//地図の画面が変更されるたびに口技を計算
onRegionChangeComplete=(地区)=>{
//111キロメートルから中心点から縦幅、横幅を計算
常数中心=点([区域.经度,区域.纬度])
常数垂直仪=111*region.latitudeDelta/2
常数水平仪=111*region.longitudeDelta/2
//実際の距離を計算
常量选项={units:'km'}
常数南=目的地(中心、垂直仪、180、选项)
const west=目的地(中心,水平仪,-90,选项)
常数北=目的地(中心、垂直仪、0、选项)
常数东=目的地(中心、水平仪、90、选项)
//計算結果(GeoJson)から口技を保存する
这是我的国家({
南:南。几何。坐标[1],
西:西。几何。坐标[0],
北:北。几何。坐标[1],
东:东。几何。坐标[0],
})
}
fetchToilet=async()=>{
const south=this.state.south
const west=this.state.west
const north=this.state.north
const east=this.state.east
//テンプレートリテラルを使って口技を展開
常数体=`
[out:json];
(
节点
[舒适=幼儿园]
(${south}、${west}、${north}、${east});
);
出来
`
//取回関数に渡す选项を指定
常量选项={
方法:“POST”,
身体:身体
}
//取回関数で天桥空气污染指数のエントリポイントにアクセスし、取得したJSONを保存
试一试{
const response=等待获取('https://overpass-api.de/api/interpreter,选项)
const json=await response.json()
this.setState({elements:json.elements})
}捕获(e){
控制台日志(e)
}
}
render(){
返回(
{
this.state.elements.map((element)=>{
让标题=”保育園"
if(element.tags[“name”]!==未定义){
title=element.tags[“name”]
}
返回()
})
}
this.fetchToilet()}
style={style.button}
>
保育園取得
);
}
}
const styles=StyleSheet.create({
容器:{
弹性:1,
背景颜色:“#fff”,
对齐项目:“居中”,
justifyContent:“柔性端”,
},
地图视图:{
…StyleSheet.absoluteFillObject,
},
按钮容器:{
flexDirection:“行”,
澳门时间:20,,
背景颜色:'透明',
对齐项目:'中心',
},
按钮:{
宽度:150,
对齐项目:'中心',
辩护内容:'中心',
背景颜色:'rgba(255235255,0.7)',
水平方向:18,
填充垂直:12,
边界半径:20,
},
按钮项:{
textAlign:“中心”,
},
});

您可以使用
世博会地点
软件包在世博会应用程序中获取用户的当前地点。以下是官方信息


链接到


您已将此代码添加到
componentDidMount
useffect
钩子中,以在每次打开应用程序时获取用户位置

import * as Location from "expo-location";
从“React”导入React;
从“react native”导入{样式表、文本、视图、TouchableOpacity};
从“react native maps”导入MapView;
从'@turf/helpers'导入{point};
从“@turp/destination”导入目的地;
从“世博会地点”导入*作为地点;
导出默认类App扩展React.Component{
建造师(道具){
超级(道具);
此.state={
要素:[],
南:空,
韦斯特:空,
北:空,
东:空,
纬度:35.681236,
经度:139.767125,
};
}
新屋(位置){
这是我的国家({
…这个州,
纬度:location.coords.latitude,
经度:location.coords.longitude,
});
}
异步组件didmount(){
试一试{
让{status}=wait Location.requestPermissionsAsync();
如果(状态!=“已授予”){
返回;
}
let location=await location.getCurrentPositionAsync({});
这是一个不动产(地点);
}捕获(错误){
console.log(错误);
}
}
onRegionChangeComplete=(地区)=>{
常数中心=点([区域.经度,区域.纬度]);
常数垂直仪=(111*区域纬度德尔塔)/2;
常数水平仪=(111*区域纵向德尔塔)/2;
常量选项={单位:'公里'};
常数南=目的地(中心、垂直仪、180、选项);
康斯特韦斯特=德斯
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import MapView from 'react-native-maps';
import { point } from '@turf/helpers';
import destination from '@turf/destination';
import * as Location from 'expo-location';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      elements: [],
      south: null,
      west: null,
      north: null,
      east: null,
      latitude: 35.681236,
      longitude: 139.767125,
    };
  }

  updateState(location) {
    this.setState({
      ...this.state,
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
    });
  }

  async componentDidMount() {
    try {
      let { status } = await Location.requestPermissionsAsync();
      if (status !== 'granted') {
        return;
      }
      let location = await Location.getCurrentPositionAsync({});
      this.updateState(location);
    } catch (error) {
      console.log(error);
    }
  }

  onRegionChangeComplete = (region) => {
    const center = point([region.longitude, region.latitude]);
    const verticalMeter = (111 * region.latitudeDelta) / 2;
    const horizontalMeter = (111 * region.longitudeDelta) / 2;
    const options = { units: 'kilometers' };
    const south = destination(center, verticalMeter, 180, options);
    const west = destination(center, horizontalMeter, -90, options);
    const north = destination(center, verticalMeter, 0, options);
    const east = destination(center, horizontalMeter, 90, options);
    this.setState({
      south: south.geometry.coordinates[1],
      west: west.geometry.coordinates[0],
      north: north.geometry.coordinates[1],
      east: east.geometry.coordinates[0],
    });
  };

  fetchToilet = async () => {
    const south = this.state.south;
    const west = this.state.west;
    const north = this.state.north;
    const east = this.state.east;
    const body = `
            [out:json];
            (
                node
                [amenity=kindergarten]
                (${south},${west},${north},${east});

            );
            out;
            `;

    const options = {
      method: 'POST',
      body: body,
    };

    try {
      const response = await fetch(
        'https://overpass-api.de/api/interpreter',
        options
      );
      const json = await response.json();
      this.setState({ elements: json.elements });
    } catch (e) {
      console.log(e);
    }
  };
  render() {
    return (
      <View style={styles.container}>
        <MapView
          onRegionChangeComplete={this.onRegionChangeComplete}
          style={styles.mapView}
          showsUserLocation
          initialRegion={{
            latitude: this.state.latitude,
            longitude: this.state.longitude,
            latitudeDelta: 0.02, 
            longitudeDelta: 0.02,
          }}>
          {this.state.elements.map((element) => {
            let title = '保育園';
            if (element.tags['name'] !== undefined) {
              title = element.tags['name'];
            }
            return (
              <MapView.Marker
                coordinate={{
                  latitude: element.lat,
                  longitude: element.lon,
                }}
                title={title}
                key={'id_' + element.id}
              />
            );
          })}
        </MapView>

        <View style={styles.buttonContainer}>
          <TouchableOpacity
            onPress={() => this.fetchToilet()}
            style={styles.button}>
            <Text style={styles.buttonItem}>保育園取得</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'flex-end',
  },

  mapView: {
    ...StyleSheet.absoluteFillObject,
  },

  buttonContainer: {
    flexDirection: 'row',
    marginVertical: 20,
    backgroundColor: 'transparent',
    alignItems: 'center',
  },

  button: {
    width: 150,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(255,235,255,0.7)',
    paddingHorizontal: 18,
    paddingVertical: 12,
    borderRadius: 20,
  },

  buttonItem: {
    textAlign: 'center',
  },
});