简体   繁体   English

如何在地图上获取固定位置名称?

[英]How to get pinned location name on map?

I have created an android app with CRNA, I can get the current location of the user by Expo's location API. 我用CRNA创建了一个Android应用程序,我可以通过Expo的位置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>
    );
  }
}

For that you need to use some for of geocoding. 为此,您需要使用一些进行地理编码。

In general look at the google maps page about geocoding . 一般来说,请查看有关地理编码的Google地图页面。 And here is an npm package for react native. 这是一个反应原生的npm包

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: 所以我创建了一个像这样的redux动作,它很好地解决了我的问题:

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM