自动获取地址天气Android,用高德地图获取位置并自动获取天气 react-native-smart-amap-location...

本模块讲述的是自动获取当前位置,并获取当前天气

c22b56368ddf33ab8eec19a0e87f76d3.png

242177e44ad23f6363823c79e2260aaa.png

思路:1.获取到当前位置;2.根据当前位置去获取天气

第一步:获取到当前位置

我这里用的是高德地图react-native-smart-amap-location这个组件获取当前位置

具体操作:

Android部分:

需要用到两个组件,

安装:

npm install react-native-smart-amap-location --save

npm install react-native-smart-app-event-listener-enhance --save

配置:

1.在 android\settings.gradle 中添加

include ':react-native-smart-amap-location'

project(':react-native-smart-amap-location').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-smart-amap-location/android')

2.在 android\app\build.gradle 中

dependencies {

compile project(':react-native-smart-amap-location')//添加此行

}

3.在 MainApplication.java 中 添加

import com.reactnativecomponent.amaplocation.RCTAMapLocationPackage;//添加此行

.............

@Override

protected ListgetPackages() {

return Arrays.asList(

..........

new RCTAMapLocationPackage(),//添加此行

.......

);

}

4.在 AndroidManifest.xml 中添加权限

并 在 application 中添加如下代码,并把从  高德地图API申请的key   填写到下面value处

可能出现的错误:

1.No resource found that matches the given name: attr 'android:keyboardNavigationCluster'

解决方法:

到相应组件的 android\bulid.gradle 中 ,改为26 及 26.0.1

compileSdkVersion 26

buildToolsVersion "26.0.1"

和 依赖也改为 26.0.1

dependencies {

compile 'com.android.support:appcompat-v7:26.0.1'

}

2.在运行中可能出现一个在 node_modules\react-native-smart-amap-location\android\src\main\java\com\reactnativecomponent\amaplocation\RCTAMapLocationPackage.java  中 第22行  @Override  的错误,

此时需要将 这个方法删掉即可

例子代码:

import React, { Component } from 'react';

import {

View, TextInput, Keyboard, Text, KeyboardAvoidingView, Image, StyleSheet, NetInfo, Platform, Alert,

ImageBackground, ScrollView, DeviceEventEmitter, TouchableOpacity, StatusBar,

NativeAppEventEmitter, ProgressBarAndroid, ActivityIndicator, Dimensions

} from 'react-native';

import { InputItem, Button, WingBlank, Toast, Checkbox, Modal } from 'antd-mobile-rn';

import AMapLocation from 'react-native-smart-amap-location';

import AppEventListenerEnhance from 'react-native-smart-app-event-listener-enhance'

const duration = 20000;

//fetch扩展,加入超时功能.

const fetchPlus = (url, config) => {

let fetch_promise = fetch(url, config);

let time_promise = new Promise((resolve, reject) => {

setTimeout(() => {

reject(new Error('请求超时'));

}, duration);

});

return Promise.race([fetch_promise, time_promise]);

}

const width = Dimensions.get('window').width;

class Test extends Component {

static navigationOptions = ({navigation,screenProps}) => ({

// 这里面的属性和App.js的navigationOptions是一样的。

header : null

});

constructor(props) {

super(props);

this.state = {

addLoading:true,

weaLoading:true,

address:'',

weather:'',

};

}

async show(district){

console.log("地区;",district);

try{

let url = `http://wthrcdn.etouch.cn/weather_mini?city=${district}`;

let response = await fetchPlus(url);

let result = await response.json();

console.log("singleGetList result:",result);

debugger;

this.setState({

weather:result,

weaLoading:false,

})

return result;

}catch (e){

Toast.info('发生未知错误')

this.setState({

weaLoading:false,

})

}

}

componentDidMount() {

AMapLocation.init(null);

this._showReGeocode();

this.addAppEventListener(

NativeAppEventEmitter.addListener('amap.location.onLocationResult', this._onLocationResult)

)

}

componentWillUnmount () {

//停止并销毁定位服务

AMapLocation.cleanUp()

}

//单次定位并返回逆地理编码信息

_showReGeocode = () => {

console.log("bbbbbbbbb");

this.setState({

loading: true,

})

AMapLocation.getReGeocode()

}

_onLocationResult = (result) => {

this.setState({

addLoading:false,

})

if(result.error) {

Alert.alert(`错误代码: ${result.error.code}, 错误信息: ${result.error.localizedDescription}`)

}

else {

if(result.formattedAddress) {

console.log("地址:"+result.city+"-"+result.district);

let r ='';

if(result.district){

r= this.show(result.district);

}else{

r= this.show(result.city);

}

this.setState({

address:result,

addLoading:false,

})

}

else {

Alert.alert(`纬度 = ${result.coordinate.latitude}, 经度 = ${result.coordinate.longitude}`)

}

}

}

showWeather(item,key){

console.log("aaa")

if(key!==0){

return(

{item.date}

{item.type}

{item.high.split(' ')[1]+' / '+item.low.split(' ')[1]}

)

}

}

render() {

let address = this.state.address;

let weather = this.state.weather;

debugger

return (

{

this.state.addLoading?

定位中......

:

{address!==''&&(address.city+"-"+address.district)}

}

{

!this.state.weaLoading?

{weather!==''&&weather.data.wendu+' ℃'}

{weather!==''&&weather.data.forecast[0].type}

{weather!==''&&weather.data.forecast[0].high.split(' ')[1]+' / '+weather.data.forecast[0].low.split(' ')[1]}

{weather!==''&&weather.data.forecast[0].fengxiang+weather.data.forecast[0].fengli.split(']')[0].slice(9)}

{weather!==''&&weather.data.ganmao}

:

正在获取天气......

}

{

weather!==''&& weather.data.forecast.map((item,key)=> this.showWeather(item,key))

}

);

}

}

export default AppEventListenerEnhance(Test);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值