react-native 使用百度地图

声明:本文使用的是作者未更新之前的低版本,不是最新的版本(看仔细在配置)

低版本号为:"react-native-baidu-map": "^0.6.0" ,前往1.0.6版

在 Xcode 9.4上运行,10.1运行编译有问题

GitHub:https://github.com/lovebing/react-native-baidu-map


先到百度地图创建应用:

申请开发版SHA1:

打开终端,输入命令:cd .android,回车继续输入以下命令

keytool -list -v -keystore debug.keystore  

口令默认为 android

 

得到开发版 SHA1

 

发布版 SHA1:以 Android Stutio 为例(Keytool生成看最下面):

打开 build => Generate Signed APK

选择新建:

 

一路 next  最后 finish,在项目 android/app 下生成一个 .keystore 文件

继续在命令行中输入 

keytool -list -v -keystore   apk的keystore(文件路径)

接下来输入刚才的密码:

得到发布版 SHA1:

 

Keytool -genkey -alias my-release-keystore.keystore -keyalg RSA -validity 20000 -keystore my-release-keystore.keystore

keytool工具是Java JDK自带的证书工具
-genkey参数表示:要生成一个证书(版权、身份识别的安全证书)
-alias参数表示:证书有别名,-alias fantongyo.keystore表示证书别名为:my-release-keystore
-keyalg RSA表示加密类型,RSA表示需要加密,以防止别人盗取
-validity 20000表示有效时间20000天
-keystore my-release-keystore.keystore表示要生成的证书名称为my-release-keystore

--------------------------------------------------------------------------------------------

输入命令:Keytool -genkey -alias my-release-keystore.keystore -keyalg RSA -validity 20000 -keystore my-release-keystore.keystore,到最后提示keytool 错误: java.io.FileNotFoundException: MyAndroidKey.keystore (Permission denied).

原因:缺少权限

方法一更改保存目录:就是讲jdk从c盘挪到其它盘。

方法二更改权限:以管理员身份运行CMD,MAC 下添加 sudo 

sudo Keytool -genkey -alias my-release-keystore.keystore -keyalg RSA -validity 20000 -keystore my-release-keystore.keystore

 

安装 npm i react-native-baidu-map --save

android配置:

在项目的 android/settings.gradle目录 下添加:

include ':react-native-baidu-map'
project(':react-native-baidu-map').projectDir = new File(settingsDir, '../node_modules/react-native-baidu-map/android')

 在android/app/build.gradle 中添加

    signingConfigs {
        release {
            storeFile file(MYAPP_RELEASE_STORE_FILE)
            storePassword MYAPP_RELEASE_STORE_PASSWORD
            keyAlias MYAPP_RELEASE_KEY_ALIAS
            keyPassword MYAPP_RELEASE_KEY_PASSWORD
        }
    }
    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }
    }
    dependencies {
      implementation project(':react-native-baidu-map') // 添加的一行
      ...
    } 

在gradle.properties中添加

MYAPP_RELEASE_STORE_FILE=my-release-keystore.keystore
MYAPP_RELEASE_KEY_ALIAS=my-release-keystore.keystore (和自己之前起的文件名要一致)
MYAPP_RELEASE_STORE_PASSWORD=****** (自己设置的密码)
MYAPP_RELEASE_KEY_PASSWORD=******

在android/app/src/main/AndroidManifest.xml 中添加

    <uses-permission android:name="android.permission.INTERNET" />
    <!-- 这个权限用于进行网络定位-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- 这个权限用于访问GPS定位-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
  ...
  <meta-data
  android:name="com.baidu.lbsapi.API_KEY"
  android:value="I03Xwhn5L3uVBrYSRfG8KzSrSZQkaM8h"/> // 申请到的baidu地图app key 
  ...
  </application>

MainApplication.java 中添加:

    import org.lovebing.reactnative.baidumap.BaiduMapPackage; //添加

    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
              new BaiduMapPackage(getApplicationContext()) //add this
      );
    }

在node_modules/react-native-baidu-map中修改 MapView.js

修改前:
import React, {
  Component,
  PropTypes
} from 'react';

修改后:
import React, {
  Component,
} from 'react';
import PropTypes from 'prop-types'

在node_modules/react-native-baidu-map/android 下修改 BaiduMapPackage.java

删除或注释第 49 行的:@Override

 

ios 配置:

1、Project navigator->Libraries->Add Files to 选择 react-native-baidu-map/ios/RCTBaiduMap.xcodeproj

2、Project navigator->Build Phases->Link Binary With Libraries 加入 libRCTBaiduMap.a

继续添加依赖,点击 Add Other:

 

3、Project navigator->Build Settings->Search Paths,

Framework search paths 添加 $(SRCROOT)/../node_modules/react-native-baidu-map/ios/lib,

Header search paths 添加 $(SRCROOT)/../node_modules/react-native-baidu-map/ios/RCTBaiduMap

(也可以在node_modules文件下将对应文件直接拖进去,感谢@_摩西_的提醒)

4、添加依赖, react-native-baidu-map/ios/lib 下的全部 framwordk, CoreLocation.framework和QuartzCore.framework、OpenGLES.framework、SystemConfiguration.framework、CoreGraphics.framework、Security.framework、libsqlite3.0.tbd(xcode7以前为 libsqlite3.0.dylib)、CoreTelephony.framework 、libstdc++.6.0.9.tbd(xcode7以前为libstdc++.6.0.9.dylib)

添加方法同第二步,

5、添加 BaiduMapAPI_Map.framework/Resources/mapapi.bundle

将node_modules/react-native-baidu-map/ios/lib/BaiduMapAPI_Map.framework/Resources/mapapi.bundle拖进xcode与项目同名的文件夹下

6、AppDelegate.m init 初始化

#import "RCTBaiduMapViewManager.h"

//百度地图

  [RCTBaiduMapViewManager initSDK:@"api key"];

 

1、error: Redefinition of ‘RCTMethodInfo’ :

2、error: 'RCTViewManager.h' file not found

 

js代码:

import React, { Component } from 'react';

import {
    StyleSheet,
    Text,
    View,
    ScrollView,
    Platform,
} from 'react-native';

import { MapView,MapTypes,Geolocation} from 'react-native-baidu-map';

import Dimensions from 'Dimensions';
const { width,height } = Dimensions.get('window');

export default class BaiduMapDemo extends Component {
    constructor() {
        super();
        this.state = {
            zoomControlsVisible: true,
            trafficEnabled: false,
            baiduHeatMapEnabled: false,
            mapType: MapTypes.NORMAL,
            zoom: 15,
            center: {
                longitude: 113.896198,
                latitude: 22.959144,
            },
            markers: [
                {
                    longitude: 113.896198,
                    latitude: 22.959144,
                    title: 'title',
                }
            ],
            clickMessage: '',
            poiMessage: '',
        };
    }

    componentDidMount() {
        
    }

  render() {
        return (
            <ScrollView style={styles.container}>
                <MapView 
                    zoomControlsVisible={this.state.zoomControlsVisible} //默认true,是否显示缩放控件,仅支持android
                    trafficEnabled={this.state.trafficEnabled} //默认false,是否显示交通线
                    baiduHeatMapEnabled={this.state.baiduHeatMapEnabled} //默认false,是否显示热力图
                    mapType={this.state.mapType} //地图模式,NORMAL普通 SATELLITE卫星图
                    zoom={this.state.zoom} //缩放等级,默认为10
                    center={this.state.center} // 地图中心位置
                    markers={this.state.markers} //地图多个标记点

                    onMapLoaded={(e) => { //地图加载事件
                        Geolocation.getCurrentPosition()
                            .then(data => {
                                console.log(data)
                                // this.setState({
                                //     center: {
                                //         longitude: data.longitude,
                                //         latitude: data.latitude
                                //     },
                                //     markers: [{
                                //         longitude: data.longitude,
                                //         latitude: data.latitude,
                                //         title: data.district + data.street
                                //     }]
                                // })
                            })
                            .catch(e =>{
                                console.warn(e, 'error');
                            })
                    }}
                    
                    onMarkerClick={(e) => { //标记点点击事件
                        console.log(e)
                    }}
                    onMapClick={(e) => { //地图空白区域点击事件,返回经纬度
                        let title = '';
                        Geolocation.reverseGeoCode(e.latitude,e.longitude)
                            .then(res => {
                                console.log(res)
                                Platform.OS == 'ios' ? 
                                    title = res.district + res.streetName
                                :
                                    title = res.district + res.street;
                                this.setState({
                                    center: {
                                        longitude: e.longitude,
                                        latitude: e.latitude,
                                    },
                                    markers: [{
                                        longitude: e.longitude,
                                        latitude: e.latitude,
                                        title: title,
                                    }],
                                    clickMessage: JSON.stringify(res)
                                })
                            })
                            .catch(err => {
                                console.log(err)
                            })
                        
                    }}
                    onMapPoiClick={(e) => { //地图已有点点击
                        Geolocation.reverseGeoCode(e.latitude,e.longitude)
                            .then(res => {
                                res = JSON.stringify(res)
                                this.setState({
                                    center: {
                                        longitude: e.longitude,
                                        latitude: e.latitude,
                                    },
                                    markers: [{
                                        longitude: e.longitude,
                                        latitude: e.latitude,
                                        title: e.name,
                                    }],
                                    poiMessage: res
                                })
                            })
                            .catch(err => {
                                console.log(err)
                            })
                    }}
                    style={styles.map}
                >
                </MapView>

                <View style={styles.list}>
                    <Text>地图缩放控件状态: </Text>
                    {this.state.zoomControlsVisible ? 
                        <Text onPress={() => this.setState({zoomControlsVisible:false})}>显示</Text>
                        :
                        <Text onPress={() => this.setState({zoomControlsVisible:true})}>关闭</Text>
                    }
                </View>
                <View style={styles.list}>
                    <Text>交通线状态: </Text>
                    {this.state.trafficEnabled ? 
                        <Text onPress={() => this.setState({trafficEnabled:false})}>显示</Text>
                        :
                        <Text onPress={() => this.setState({trafficEnabled:true})}>关闭</Text>
                    }
                </View>
                <View style={styles.list}>
                    <Text>热力图状态: </Text>
                    {this.state.baiduHeatMapEnabled ? 
                        <Text onPress={() => this.setState({baiduHeatMapEnabled:false})}>显示</Text>
                        :
                        <Text onPress={() => this.setState({baiduHeatMapEnabled:true})}>关闭</Text>
                    }
                </View>
                <View style={styles.list}>
                    <Text>地图模式状态: </Text>
                    {this.state.mapType == MapTypes.NORMAL ? 
                        <Text onPress={() => this.setState({mapType:MapTypes.SATELLITE})}>普通</Text>
                        :
                        <Text onPress={() => this.setState({mapType:MapTypes.NORMAL})}>卫星</Text>
                    }
                </View>
                <View style={styles.list}>
                    <Text>地图空白区域点击信息: </Text>
                </View>
                <View style={styles.list}>
                    <Text>{this.state.clickMessage}</Text>
                </View>
                <View style={styles.list}>
                    <Text>地图已有点点击信息: </Text>
                </View>
                <View style={styles.list}>
                    <Text>{this.state.poiMessage}</Text>
                </View>
                <View style={styles.list}>
                    <Text onPress={() => {
                        Geolocation.getCurrentPosition()
                            .then(data => {
                                console.log(data)
                                this.setState({
                                    center: {
                                        longitude: data.longitude,
                                        latitude: data.latitude
                                    },
                                    markers: [{
                                        longitude: data.longitude,
                                        latitude: data.latitude,
                                        title: data.district + data.street
                                    }]
                                })
                            })
                            .catch(e =>{
                                console.warn(e, 'error');
                            })
                    }}>当前位置</Text>
                </View>
            </ScrollView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
    },
    map: {
        width: width,
        height: height - 300,
        marginBottom: 5,
    },
    list: {
        flexDirection: 'row',
        paddingLeft: 10,
        marginBottom: 5,
    }
});

 

ios效果图:

android效果图:

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值