0

我已经创建了一个带有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> 
    ); 
    } 
} 

回答

0

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

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

0

随着我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) 
相关问题