1

I have created an android app with CRNA, I can get the current location of the user by Expo's location API. But I can't figure out how to get the city name of a pinned location? This is my code so far:

class Map extends Component {
  constructor(props) {
    super(props);
    this.state = {
      region: {
        latitude: 41.0141977,
        longitude: 28.9638121,
        latitudeDelta: 0.1,
        longitudeDelta: 0.05,
      },
      x: {
        latitude: 41.0238343,
        longitude: 29.0335236,
      },
      regionName: "",
    }
  }

  onDragEnd(e) {
    this.setState({x: e.nativeEvent.coordinate});
  }

  onRegionChange(region) {
    this.setState({region});
  }

  render() {
    return (
      <Modal
        animationType={"slide"}
        transparent={true}
        visible={this.props.visible}
        onRequestClose={this.props.changeState}
        style={styles.modal}
      >
        <MapView
          region={this.state.region}
          onRegionChange={this.onRegionChange.bind(this)}
          style={styles.map}
        ><MapView.Marker draggable
                         coordinate={this.state.x}
                         onDragEnd={this.onDragEnd.bind(this)}

        /></MapView>
      </Modal>
    );
  }
}

2 Answers2

0

For that you need to use some for of geocoding.

In general look at the google maps page about geocoding. And here is an npm package for react native.

Milan Gulyas
  • 632
  • 8
  • 18
0

As I googled more and more I learnt it's called reverse geocoding. So I created an redux action like this and it solved my problem very well:

 export function fetchCityName(lat, lng) {
  const link = `http://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}`;
  return dispatch => {
    dispatch(startFetch());

    return fetch(link)
      .then(response => response.json())
      .then(responseJson => {
        const addressComponent = _.get(responseJson, 'results[0].address_components', []);
        const getAreaName = zone => _.get(
          addressComponent,
          `[${_.findIndex(addressComponent, obj => _.includes(obj.types, zone))}].long_name`
        );

        const region = ' ' + getAreaName('administrative_area_level_1');
        const country = ' ' + getAreaName('country');
        const region2 = getAreaName('administrative_area_level_2');

        const location = region2 ?
          [region2, region, country].toString() :
          region.concat(',' + country);

        dispatch(getCityName(location));
      })
      .catch(console.error)