美文网首页
ReactNative 调用高德的web选址组件实现地图选点

ReactNative 调用高德的web选址组件实现地图选点

作者: 入魔佳乐家 | 来源:发表于2019-07-22 11:52 被阅读0次

引言

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

高德选址组件

https://lbs.amap.com/api/lightmap/guide/picker/

image.png

在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)
        }}
      />

相关文章

网友评论

      本文标题:ReactNative 调用高德的web选址组件实现地图选点

      本文链接:https://www.haomeiwen.com/subject/hnyilctx.html