Expo - need help to geofence a radius around API location data

Trying to geofence a radius for current location to an API that has locations. Currently the new EXPO SDK has now launched the geofencing alongside using the taskManager to manage the request.

This is a proof of concept and does the new SDK actually work for the requirement.

Can get the current location. Able to show all data from the API (with latitude and longitude)

Now it is to let the current location only display locations from the API to a certain radius.

For now I dont need to run background tasks and updating the current location - its more about being in one location and then pulling locations within the radius from the API.

Any help or online tutorials will help.

Running this in EXPO snack for the proof of concept.

As the geofencing options is very new to the SDK - online tutorials are not avaiable and with a lot of searching most users are not getting the final results.

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

TaskManager.defineTask('geoTask', ({ data: { eventType, region }, error }) => {
  if (error) {
    console.log("geoTaskError", {error});
    return;
  }
  if (eventType === Location.GeofencingEventType.Enter) {
    console.log("geoTaskEnter", { eventType, region });
  } 
  else if (eventType === Location.GeofencingEventType.Exit) {
    console.log("geoTaskExit", { eventType, region });
  }
});


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({ locationLat: (location.coords.latitude) });
    this.setState({ locationLon: (location.coords.longitude) });
    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 }});
  };

  _startGeofencingAsync = async (geoTask, regions) => {
  this.setState ({ regions: {radius: 4000}})
  };

  renderItem = ({item}) => {
    return (
    <View>
      <View>
        <Text>CODE: {item.code}
        <Text> AIRPORT NAME: {item.name}
        <Text> LAT: {item.lat}
        <Text> LONG: {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)    
    });

    let onPress = async () => {
    await Location.startLocationUpdatesAsync('geoTask', {
      accuracy: Location.Accuracy.Balanced,
    });
  };
  }

  render() {
    return (
      <View style={styles.container}>

        <Text>Latitude: {this.state.locationLat}</Text>
        <Text>Longitude: {this.state.locationLon}</Text>
        <Text>Location: {this.state.locationResult}</Text>

      <View style={styles.container}>
        <FlatList
          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',
  },
});
1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.