Expo - Реагируйте на собственный GeoFence с данными API - PullRequest
0 голосов
/ 02 мая 2019

Я пытаюсь работать над простым доказательством концепции геозоны вокруг определенных широт и долгот

Структура: - служба определения местоположения включена (теперь не требуется фоновых обновлений, только начальное местоположение) - местоположение пользователя определено - просматривает данные местоположений в файле json и находит их в непосредственной близости @ 10 км (см. URL для API)

EXPO недавно обновил SDK, чтобы управлять этим, но при просмотре нескольких поисков ничего не приходит в голову при управлении простой задачей размещения статического местоположения в базе данных, а затем запускает радиус близости.

Использование базовой настройки для концепции, но не уверен, что следующие шаги ... Ниже приведена настройка, которая у меня есть на данный момент, и мне хотелось бы узнать о том, где начинаются вызовы GeoFence

import React, {Component} from 'react';
    import { AppRegistry, Text, View, StyleSheet, FlatList, Image } from 'react-native';
    import { Constants, MapView, Location, Permissions } from 'expo';

export default class App extends Component {
  constructor() {
    super ()
    this.state = {
      dataSource: []
    }
  }

  state = {
    mapRegion: null,
    hasLocationPermissions: false,
    locationResult: null
  };

  _handleMapRegionChange = mapRegion => {
    console.log(mapRegion);
    this.setState({ mapRegion });
  };

  _getLocationAsync = async () => {
   let { status } = await Permissions.askAsync(Permissions.LOCATION);
   if (status !== 'granted') {
     this.setState({
       locationResult: 'Permission to access location was denied',
     });
   } else {
     this.setState({ hasLocationPermissions: true });
   }

   let location = await Location.getCurrentPositionAsync({});
   this.setState({ locationResult: JSON.stringify(location) });

   // Center the map on the location we just fetched.
    this.setState({mapRegion: { latitude: location.coords.latitude, longitude: location.coords.longitude, latitudeDelta: 0.0922, longitudeDelta: 0.0421 }});
  };

  renderItem = ({item}) => {
    return (
    <View>
      <View>
        <Text>{item.code}  
        <Text>{item.name} 
        <Text>{item.lat} 
        <Text>{item.lon} 
        </Text>
        </Text>
        </Text>
        </Text>
      </View>
    </View>
  )}

  componentDidMount() {
    this._getLocationAsync();
    //const url = 'https://www.json-generator.com/api/json/get/ccLAsEcOSq?indent=1'
    const url = 'https://gist.githubusercontent.com/tdreyno/4278655/raw/7b0762c09b519f40397e4c3e100b097d861f5588/airports.json'
    fetch(url)
    .then((repsonse) => repsonse.json())
    .then((responseJson) => {
      this.setState({
        dataSource: responseJson
      })
    })
    .catch((error) => {
        console.log(error)
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>
          Pan, zoom, and tap on the map!
        </Text>

        {
          this.state.locationResult === null ?
          <Text>Finding your current location...</Text> :
          this.state.hasLocationPermissions === false ?
            <Text>Location permissions are not granted.</Text> :
            this.state.mapRegion === null ?
            <Text>Map region doesn't exist.</Text> :
            <MapView
              style={{ alignSelf: 'stretch', height: 200 }}
              region={this.state.mapRegion}
              onRegionChange={this._handleMapRegionChange}
            />
        }

        <Text>
          Location: {this.state.locationResult}
        </Text>

      <View style={styles.container}>
        <FlatList
          //={[{ key: 'a'}, { key: 'b'}]}
          //renderItem={({item }) => <Text>{item.key}</Text>}
          data={this.state.dataSource}
          renderItem={this.renderItem}
          />
      </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Это всего лишь подтверждение концепции, и мне просто нужно несколько указаний, которые помогут мне двигаться дальше. Ссылки и учебники все помогут

Спасибо (все еще учусь)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...