【问题标题】:How to get pinned location name on map?如何在地图上获取固定位置名称?
【发布时间】:2017-06-21 08:57:57
【问题描述】:

我用 CRNA 创建了一个 android 应用程序,我可以通过 Expo 的位置 API 获取用户的当前位置。但我不知道如何获取固定位置的城市名称?到目前为止,这是我的代码:

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>
    );
  }
}

【问题讨论】:

    标签: android react-native expo react-native-maps create-react-native-app


    【解决方案1】:

    为此,您需要使用一些地理编码。

    一般看谷歌地图页面about geocoding。 这里是一个 npm package 用于反应原生。

    【讨论】:

      【解决方案2】:

      随着我越来越多地在 Google 上搜索,我了解到它称为反向地理编码。所以我创建了一个这样的 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)
      

      【讨论】:

        猜你喜欢
        • 2012-09-18
        • 1970-01-01
        • 1970-01-01
        • 2011-08-29
        • 1970-01-01
        • 2018-03-08
        • 2014-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多