HTML代碼(MVC)
@*-------------------調用地圖接口在百度地圖的基礎上,添加自動搜索(地區)框----------------------------------*@ @{ Layout = null; } <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=CGkMErD3Gux07tGL26GCoWGU"></script> @*搜索框*@ <div style="margin:50px">請輸入:<input type="text" id="suggestId" size="30" placeholder="搜索地區、" style="width:300px;" /></div> @*搜索結果*@ <div id="searchResultPanel" style="border:1px solid green;width:300px;height:600px;position:absolute;left: 650px;top:20px;"></div> @*添加地圖的地方*@ <div id="container"></div>
JS代碼
<script type="text/javascript"> //初始化地圖 var map = new BMap.Map("container");//在百度地圖容器中創建一個地圖 var point = new BMap.Point(116.3964, 39.9093);//定義一個中心點坐標 map.centerAndZoom(point, 5);//設定地圖的中心點和坐標並將地圖顯示在地圖容器中 map.enableScrollWheelZoom();//允許鼠標滑輪放大或縮小 var ac = new BMap.Autocomplete( //建立一個自動完成的對象 { "input": "suggestId", "location": map }); function G(id) { return document.getElementById(id); } ac.addEventListener("onhighlight", function (e) { //鼠標放在下拉列表上的事件 var str = ""; var _value = e.fromitem.value; var value = ""; if (e.fromitem.index > -1) { value = _value.province + _value.city + _value.district + _value.street + _value.business; } str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value; value = ""; if (e.toitem.index > -1) { _value = e.toitem.value; value = _value.province + _value.city + _value.district + _value.street + _value.business; } str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value; G("searchResultPanel").innerHTML = str; }); var myValue; ac.addEventListener("onconfirm", function (e) { //鼠標點擊下拉列表后的事件 var _value = e.item.value; myValue = _value.province + _value.city + _value.district + _value.street + _value.business; G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue; setPlace(); }); function setPlace() {// 創建地址解析器實例 var myGeo = new BMap.Geocoder();// 將地址解析結果顯示在地圖上,並調整地圖視野 myGeo.getPoint(myValue, function (point) { if (point) { map.centerAndZoom(point, 9);//重新定位地圖中心點 map.addOverlay(new BMap.Marker(point));//創建一個地圖標注 } }, "北京"); } </script> <style type="text/css"> body { font-size: 13px; margin: 0px; } #container { width: 600px; height: 400px; } .label { margin-left: 20px; font-weight: bold; font-size: 14px; } </style>
