uni-app h5使用百度地图

uni-app 生成h5时,默认使用的腾讯地图,且自带的map无法使用mapSearch组件。于是就有了通过web-view嵌入页面来实现。

现贴上使用百度地图获取经度和纬度的功能,供大家参考。

在static/html/map.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题页</title>
   <style type="text/css">
   body{
       width:100%;
       margin:0px;
       background-color:#FAFAFA;margin: 0px;padding:0px;font-size: 12px;
   }
 div{width:95%;margin:10px auto;}
    input {width:75px;margin-right:2px;}#result-list{width:100%;padding:0;margin:5px 5px;} #result-list li {padding:10px;background-color:#f1f2f4;height:80px;margin:10px 2px;width:41%;float:left;/*white-space:nowrap;*/overflow:hidden;
        }#result-list li span {display:none;}
   </style>
    <!--地图标注Js文件-->
  <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js" ></script>
<script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=0IM6czqEBhOAqmrsdfsX9VTmiDOzu8"></script>
   
</head>
<body>
    <div style="">城市:<input type="text" id="txtCityName"> 关键字:<input type="text" id="txtTitle"><button onclick="search()">搜索</button><button onclick="closeWindow()">关闭</button></div> 
   <div id="content" style="display:none;">
       <div id="r-result" style="background:#fff;overflow:scroll;height: 200px;  100%;border:1px solid #ebeaba">
    <ul id='result-list'></ul>
  </div> 
</div>
      <div id="allmap" style="100%;height:300px"></div>
            <span style="color: #ff0066">*</span>在地图上标注琴行位置时,应先选择城市,确认经度,纬度,比例文本框值的正确性方可!


<script type="text/javascript">

                            var myCity = new BMap.LocalCity();
                            
                            var map = new BMap.Map("allmap");
                            myCity.get(function (result) {
                                console.log(result);
                            jQuery("#txtCityName").val(result.name);
                                map.centerAndZoom(result.center, 18);
                            });
                            map.enableScrollWheelZoom(true);
                            /*根据用户点击获得经纬度*/
                            map.addEventListener("click", function (e) {
                                console.log(e);
                                let addrInfo = e.point;
                              // jQuery('#txtMapJing').val(addrInfo.lng);
                               // jQuery('#txtMapWei').val(addrInfo.lat);
                                
                                
                            });
                               function getQuery(name) {
                                          // 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在)
                                          let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
                                          let r = window.location.search.substr(1).match(reg);
                                          console.log(r);
                                          if(r != null) {
                                              // 对参数值进行解码
                                              return decodeURIComponent(r[2]);
                                          }
                                          return null;
                                      }
                            function  closeWindow()
                            {
                                window.parent.postMessage({close:"true"}, "*");
                            }
                            function search() {
                                let cityName=jQuery("#txtCityName").val();
                                var local = new BMap.LocalSearch(map, {
                                    renderOptions: { map: map },
                                    pageCapacity: 30,
                                    
                                    onMarkersSet: function (array) {
                                       // console.log(array[0]);
                                        let arrLength = array.length;
                                        str = '';
                                        for (i = 0; i < arrLength; i++) {
                                            str += '<li>标题:' + array[i].title + '<br/>地址:' + array[i].address;
                                            if (typeof array[i].phoneNumber != 'undefined')
                                            {
                                                str += '<br/>电话:' + array[i].phoneNumber;
                                            }
                                            str += '</br><span>' + array[i].point.lng;
                                            str += ',' + array[i].point.lat + '</span></li>';
                                        }
                                        jQuery("#content").show();
                                        jQuery("#result-list").html(str);
                                    
                                        jQuery("#result-list li").bind('click', function () {
                                            let addrInfo = jQuery(this).find('span').text().split(',');
                                            window.parent.postMessage({test:{'lng':addrInfo[0],'lat':addrInfo[1]}}, "*");
                                           // jQuery('#txtMapJing').val(addrInfo[0]);
                                           // jQuery('#txtMapWei').val(addrInfo[1]);
                                            jQuery(this).css("background-color", '#eff4bc').siblings().css('background-color', '#f1f2f4');
                                            var point = new BMap.Point(addrInfo[0], addrInfo[1]);
                                            map.centerAndZoom(point, 18);
                                            
                                            // 创建地址解析器实例
                                            var myGeo = new BMap.Geocoder();
                                            // 将地址解析结果显示在地图上,并调整地图视野
                                            myGeo.getPoint("", function (point) {
                                                if (point) {
                                                    map.centerAndZoom(point, 20);
                                                    map.addOverlay(new BMap.Marker(point));
                                                } else {
                                                    alert("您选择地址没有解析到结果!");
                                                }
                                            }, cityName);
                                            
                                        });
                                    }
                                });
                             //   let Province = jQuery('#ddlProvince option:selected').text();
                               // if (Province == '') { alert('请选择省'); }
                               // let city = jQuery('#ddlCity option:selected').text();
                              //  if (city == '') { alert('请选择城市'); }
                                let qh = jQuery('#txtTitle').val();
                                if (qh == '') { alert('请填写琴行名称'); }
                           
                                map.centerAndZoom(cityName, 15);
                                local.search(cityName+qh);
                            }

</script>
</body>
</html>
View Code

注意:要使用百度地图功能,需要向百度申请AK,地址:https://lbsyun.baidu.com

申请的AK

 

需要本地测试时,请把白名单设置为*号。

在vue文件中引用

 

mounted()
        {
        let that=this;
        window.addEventListener('message', function(e) {
             if (typeof e.data.close!="undefined") 
                 {
                    that.showWebView=false;
                }
         if (typeof e.data.test!="undefined") {
               that.latitude=e.data.test.lat;
               that.longitude=e.data.test.lng;
            //alert(e.data.test.lng);
               if(confirm('是否确认选择'))
               {
                that.showWebView=false;
               }
          }
        }, false);
View Code

 

效果:

 通过搜索显示的数据

使用window.postMessage向父窗口传递消息,点击关闭窗口

function  closeWindow()
{
  window.parent.postMessage({close:"true"}, "*");
}

  

父窗口处理:

 let that=this;	
 window.addEventListener('message', function(e) {
 if (typeof e.data.close!="undefined") 
 {
 that.showWebView=false;
 }}, false);

其中:that.showWebView为在webView中加上的 v-if="showWebView" 

相关资料:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

 注意:要修改web-view的样式需要在App.vue中引用样式

iframe{height:400px !important;z-index:2000;overflow: hidden;top:50% !important}
原文地址:https://www.cnblogs.com/fogwang/p/14919184.html