引言
在ReactNative 中使用地图的选址组件 一般都会使用地图的库自己写页面,配合web api实现地图选点。这样做一方面会引入地图的sdk导致安装包增大很多,另一方面也费时费力。 在高德的官网发现高德提供了针对手机的选址组件,使用很方便。
高德选址组件
https://lbs.amap.com/api/lightmap/guide/picker/

在ReactNative中使用
在ReactNative中使用此组件需要借助WebView,用PostMessage传递消息。
1.创建html,放入服务器中,html代码如下(替换keywords与key参数)
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>地址选择</title>
<style>
body {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: 0;
}
iframe {
width: 100%;
height: 100%;
}
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<iframe
id="test"
src="https://m.amap.com/picker/?keywords=小区,写字楼,学校&key=****自己的高德地图的 Web端 key***"
></iframe>
<script>
(function() {
var iframe = document.getElementById("test").contentWindow;
document.getElementById("test").onload = function() {
iframe.postMessage("hello", "https://m.amap.com/picker/");
};
window.addEventListener(
"message",
function(e) {
window.ReactNativeWebView.postMessage(JSON.stringify(e.data));
},
false
);
})();
</script>
</body>
</html>
2.ReactNative中使用
import { WebView } from 'react-native-webview'
<WebView
ref={ref => {
this.wb = ref
}}
javaScriptEnabled
scalesPageToFit
source={{ uri: `${URL_PREFIX}/map.html` }} //网络地址,放在本地会导致postmessage失效
onMessage={nativeEvent => {
const { data } = nativeEvent.nativeEvent
// console.log(data)
}}
/>
网友评论