百度地图调用的一些技巧
发表时间:2020-09-15 20:28:37
文章作者:小编
浏览次数:
最近做项目需要调用在网页中内嵌入百度地图,并支持搜索,搜索结果点击后可以跳转到自定义的网址.
参考了百度的文档以网上的一些案例.都没发现 api2.0中,如何禁止掉百度地图载入时的默认点击弹信息窗事件.这就导致用户点击地图上的任意一个地方,都有可能弹出相应的信息窗口,然后再点击就会跳转到百度地图上去了.这个很不清真.
后来经过仔细查看百度的官方文档,终于找到一个选项.可以在初始化百度地图的时候关闭默认地图POI事件.部分代码如下:
<script> var map = new BMap.Map("map_container", {enableMapClick:false}); var geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition(function(r){ if(this.getStatus() == BMAP_STATUS_SUCCESS){ map.centerAndZoom(r.point, 12); } else { map.centerAndZoom('北京市', 12); } },{enableHighAccuracy: true}); function addMarker(map, point, pointInfo) { var marker = new BMap.Marker(point, { icon: new BMap.Symbol(BMap_Symbol_SHAPE_POINT, { scale: 1.2,//图标缩放大小 fillColor: "red",//填充颜色 fillOpacity: 1//填充透明度 }) }); map.addOverlay(marker); marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画 var h = pointInfo; var q = h.title; var u = h.address; var n = h.phoneNumber; var v = h.point; var A = v.lng + "," + v.lat; var x = q; var j = h.type; var infoWindow = createIw({ tit: q, add: u, tel: n, poi: v, type: j }); marker.addEventListener("click", function () { map.openInfoWindow(infoWindow,point); //开启信息窗口 }); } map.enableScrollWheelZoom(); //启用滚轮放大缩小,默认禁用 map.enableContinuousZoom(); //启用地图惯性拖拽,默认禁用 map.addControl(new BMap.NavigationControl()); //添加默认缩放平移控件 map.addControl(new BMap.OverviewMapControl()); //添加默认缩略地图控件 //map.addControl(new BMap.OverviewMapControl({isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT})); //右下角,打开 var search_options = { pageCapacity:30, onSearchComplete: function(results){ // 判断状态是否正确 if (localSearch.getStatus() == BMAP_STATUS_SUCCESS){ map.centerAndZoom(results.getPoi(0).point, 12); for (var i = 0; i < results.getCurrentNumPois(); i ++){ addMarker(map, results.getPoi(i).point, results.getPoi(i)); } } } }; var localSearch = new BMap.LocalSearch(map, search_options); localSearch.enableAutoViewport(); //允许自动调节窗体大小 localSearch.disableFirstResultSelection(); localSearch.search('大学'); var search_bd = $("#searchBaidu"); search_bd.on('click', function(){ map.clearOverlays();//清空原来的标注 var keyword = document.getElementById("address").value; if(!keyword){ alert("请输入搜索关键词"); return false; } localSearch.search(keyword); }); function createIw(a) { var e = a.tit; var h = a.add; var d = a.tel; var i = a.poi.lng + "," + a.poi.lat; var j = '<p class="iwContent">'; var f = a.type; var c = "地址"; if (f == 1) { c = "途径公交车" } if (f == 3) { c = "途径地铁" } j += "<em>" + c + ":</em>" + h + "<br/>"; d ? j += "<em>电话:</em>" + d + "<br/>": null; j += "<em>坐标:</em>" + i + ""; j += "</p>"; var g = e; if (g.length > 15) { g = g.substring(0, 12) + "..." } var url="?baidu-forum-"+ e.replace(/-/i, "") +'-' + i + '-' + h.replace(/-/i, ""); //title-poi-address return new BMap.InfoWindow(j, { title: '<span class="iwTitle" title="' + e + '"><a href="'+url+'" target="_blank">' + g + "</a></span>", width: 250 }); } </script>