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) 
相關問題