ReactNative 調(diào)用高德的web選址組件實(shí)現(xiàn)地圖選點(diǎn)

引言

在ReactNative 中使用地圖的選址組件 一般都會(huì)使用地圖的庫(kù)自己寫頁面,配合web api實(shí)現(xiàn)地圖選點(diǎn)。這樣做一方面會(huì)引入地圖的sdk導(dǎo)致安裝包增大很多,另一方面也費(fèi)時(shí)費(fèi)力。 在高德的官網(wǎng)發(fā)現(xiàn)高德提供了針對(duì)手機(jī)的選址組件,使用很方便。

高德選址組件

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

image.png

在ReactNative中使用

在ReactNative中使用此組件需要借助WebView,用PostMessage傳遞消息。

1.創(chuàng)建html,放入服務(wù)器中,html代碼如下(替換keywords與key參數(shù))
<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=小區(qū),寫字樓,學(xué)校&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` }} //網(wǎng)絡(luò)地址,放在本地會(huì)導(dǎo)致postmessage失效
        onMessage={nativeEvent => {
          const { data } = nativeEvent.nativeEvent
          // console.log(data)
        }}
      />
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容