高德地图API应用

高德地图官网:http://api.amap.com/javascript/

输入关键字,搜索地址功能的网页:
1.引用远程Map Api(js)网址形式(注册后获取)
2.定义个<div>,name=mapDiv,用来呈现地图
3. 下面开始写JS代码:定义地图对象var objMap,与2中的mapDiv绑定。定义var LngLats = new Array();用来保存搜索结果的坐标,防止搜索到后无法再引用。
4.传入strAddress调用PlaceSearch服务搜索,可以指定搜索区域,默认为全国
5.搜索的结果result是一个地址信息列表,内含地址坐标LatLng、名字Name等。定义callBack ()方法解析result,for迭代列表:取出LatLng,Name来实例化作为Marker对象的属性,并且设置Click,Draft事件方法用来显示Marker信息,LatLng加入LngLats数组 。最后把Marker对象加到objMap。
这样就显示地图、搜索结果标注到网页上了。
6.如果要做到搜索栏带智能感应的效果,需要加入AMap.Autocomplete插件,绑定搜索地址栏txtKeyWord,并指定事件方法,传入变动后的字符串,返回result给callBack()方法处理显示。
 
下面贴下代码吧,有点多,主要是js代码(替换掉你的key即可使用):
  1 <!--本程序用高德地图API实现关键字查询功能-->
  2 <!DOCTYPE HTML>  
  3 <html>  
  4 <head>  
  5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  6 <title>高德地图关键字查询</title>  
  7    <!-- <link rel="stylesheet" type="text/css" href="http://api.amap.com/Public/css/demo.Default.css" />  -->
  8     <style type="text/css">
  9         #mainMap {
 10             height: 775px;
 11             width: 908px;
 12         }
 13         #LngLat {
 14             width: 227px;
 15         }
 16     </style>  
 17 <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.2&key=YOU_KEY"></script>  
 18     <script type="text/javascript">
 19 //      增加地区搜索、感应功能(未做,待需要时再做)
 20 //        可以在页面上放个下拉列表 select,内容为“江苏”,“浙江”,“全国”等全国省份。根据选择的省份提示该地区下的智能感应、搜索功能。
 21 //        智能感应:function autoSearch() {//AutoOption对象}。搜索功能:search(strKeyword) {//PlaceSearchOptions类型}
 22         
 23         var mapObj; 
 24         var windowsArr = new Array();
 25         var LngLats = new Array();
 26 
 27         //地图初始化
 28         //选择坐标、中心点,加载提示智能感应控件和对应事件的方法
 29         function mapInit() {
 30             var opt = {
 31                 level: 13, //设置地图缩放级别    
 32                 center: new AMap.LngLat(116.397428, 39.90923) //设置地图中心点   
 33             };
 34             mapObj = new AMap.Map("mainMap", opt);
 35 
 36             //加载输入提示插件  
 37             mapObj.plugin(["AMap.Autocomplete"], function () {
 38                 //判断是否IE浏览器  
 39                 if (navigator.userAgent.indexOf("MSIE") > 0) {
 40                     document.getElementById("keyword").onpropertychange = autoSearch;   //建立事件方法    
 41                 }
 42                 else {
 43                     document.getElementById("keyword").oninput = autoSearch;            //建立事件方法
 44                 }
 45             });
 46         }
 47 
 48         /*以下代码实现智能感应功能*/
 49         //在输入框内容变动时执行,显示智能感应内容
 50         function autoSearch() {
 51             var keywords = document.getElementById("keyword").value;
 52             var auto;
 53             var autoOptions = {
 54                 pageIndex: 1,
 55                 pageSize: 10,
 56                 //city: "台湾" //城市,默认全国  
 57             };
 58             auto = new AMap.Autocomplete(autoOptions);
 59             //查询成功时返回查询结果  
 60             AMap.event.addListener(auto, "complete", autocomplete_CallBack);
 61             auto.search(keywords);
 62         }
 63 
 64         //回调函数:输出智能感应提示结果  
 65         function autocomplete_CallBack(data) {
 66             var resultStr = "";
 67             var tipArr = [];
 68             tipArr = data.tips;
 69             if (tipArr!=undefined && tipArr.length > 0) {
 70                 for (var i = 0; i < tipArr.length; i++) {
 71                     resultStr += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById(" + (i + 1)
 72                             + ",this)' onclick='selectResult(" + i + ")' onmouseout='onmouseout_MarkerStyle(" + (i + 1)
 73                             + ",this)' style=\"font-size: 13px;cursor:pointer;padding:5px 5px 5px 5px;\">" + tipArr[i].name + "<span style='color:#C1C1C1;'>" + tipArr[i].district + "</span></div>";
 74                 }
 75             }
 76             //else {
 77             //    resultStr = "找不到结果!<br />要不试试:<br />1.请确保所有字词拼写正确<br />2.尝试不同的关键字<br />3.尝试更宽泛的关键字";
 78             //}
 79 
 80             document.getElementById("searchTips").innerHTML = resultStr;
 81             document.getElementById("searchTips").style.display = "block";
 82         }
 83         /*以上代码实现智能感应功能*/
 84 
 85 
 86         //输入提示框鼠标滑过时的样式  
 87         function openMarkerTipById(pointid, thiss) {  //根据id打开搜索结果点tip    
 88             thiss.style.background = '#CAE1FF';
 89         }
 90 
 91         //输入提示框鼠标移出时的样式  
 92         function onmouseout_MarkerStyle(pointid, thiss) {  //鼠标移开后点样式恢复    
 93             thiss.style.background = "";
 94         }
 95 
 96         /*以下代码实现按关键字搜索地址功能*/
 97         //从输入提示框中选择关键字并查询。Index是选择的关键在在智能感应框中的索引  
 98         function selectResult(index) {
 99             if (navigator.userAgent.indexOf("MSIE") > 0) {
100                 document.getElementById("keyword").onpropertychange = null;
101                 document.getElementById("keyword").onfocus = focus_callback;
102             }
103 
104             //获取智能感应框中选择的关键字  
105             var strKeyword = document.getElementById("divid" + (index + 1)).innerHTML.replace(/<[^>].*?>.*<\/[^>].*?>/g, ""); ;
106             document.getElementById("keyword").value = strKeyword;
107 
108             search(strKeyword);
109         }
110         //写入关键字后,点击“搜索”按钮搜索地址
111         function search(strKeyword) {
112             if (strKeyword == undefined) {
113                 strKeyword = document.getElementById("keyword").value;
114             }
115             document.getElementById("searchTips").style.display = "none";
116 
117             //根据选择的输入提示关键字查询  
118             mapObj.plugin(["AMap.PlaceSearch"], function () {
119                 var msearch = new AMap.PlaceSearch({
120                      //city:"台湾"    //默认全国
121                 });  //构造地点查询类  
122                 AMap.event.addListener(msearch, "complete", placeSearch_CallBack); //查询成功时的回调函数  
123                 msearch.search(strKeyword);  //关键字查询查询  
124             });
125     
126             EmptyTxtLngLat();
127         }
128 
129         //定位选择输入提示关键字,开始搜索地址
130         function focus_callback() {
131             if (navigator.userAgent.indexOf("MSIE") > 0) {
132                 document.getElementById("keyword").onpropertychange = autoSearch;
133             }
134         }
135 
136         //回调函数:输出关键字查询结果
137         function placeSearch_CallBack(data) {
138             //清空地图上的InfoWindow和Marker  
139             windowsArr = [];
140             LngLats = [];
141             mapObj.clearMap();
142             var resultStr1 = "";
143             var poiArr = data.poiList.pois; //poiList属性内含发生事件时返回兴趣点列表。类型:PoiList。内含pois属性,内容:Poi列表,类型:Array.<Poi>    
144             var resultCount = poiArr.length;
145             if (resultCount > 0) {
146                 for (var i = 0; i < resultCount; i++) {
147                     resultStr1 += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById1(" + i + ",this)' onmouseout='onmouseout_MarkerStyle(" + (i + 1) + ",this)' style=\"font-size: 12px;cursor:pointer;padding:0px 0 4px 2px; border-bottom:1px solid #C1FFC1;\"><table><tr><td><img src=\"http://webapi.amap.com/images/" + (i + 1) + ".png\"></td>" + "<td><h3><font color=\"#00a6ac\">名称: " + poiArr[i].name + "</font></h3>";
148                     resultStr1 += TipContents(poiArr[i].type, poiArr[i].address, poiArr[i].tel) + "</td></tr></table></div>";
149                     addmarker(i, poiArr[i]);
150                 }
151             }
152             else {
153                 resultStr1 = "<div>未找到结果。该地址不存在或请更换关键字</div>";
154             }
155             mapObj.setFitView();
156             document.getElementById("result").innerHTML = resultStr1;
157             document.getElementById("result").style.display = "block";
158         }
159         /*以上代码实现按关键字搜索地址功能*/
160 
161         /*以下代码实现查询结果展示功能*/
162         //鼠标滑过查询结果改变背景样式,根据id打开信息窗体  
163         function openMarkerTipById1(pointId, thisDiv) {
164             thisDiv.style.background = '#CAE1FF';
165             windowsArr[pointId].open(mapObj, LngLats[pointId]);
166             ShowLatLgn(LngLats[pointId]);
167         }
168 
169         //添加查询结果的marker和infowindow      
170         function addmarker(index, poiInfo) {
171             var lngX = poiInfo.location.getLng();
172             var latY = poiInfo.location.getLat();
173             var markerOption = {
174                 map: mapObj,
175                 icon: "http://webapi.amap.com/images/" + (index + 1) + ".png",
176                 position: new AMap.LngLat(lngX, latY),
177                 draggable: true     //设置为可拖动
178             };
179 
180             var mar = new AMap.Marker(markerOption);
181             //加入全局数组marker
182             LngLats.push(new AMap.LngLat(lngX, latY));
183 
184             var infoWindow = new AMap.InfoWindow({
185                 content: "<h3><font color=\"#00a6ac\">&nbsp;&nbsp;" + (index + 1) + ". " + poiInfo.name + "</font></h3>" + TipContents(poiInfo.type, poiInfo.address, poiInfo.tel),
186                 size: new AMap.Size(300, 0),
187                 autoMove: true,
188                 offset: new AMap.Pixel(0, -30)
189             });
190             //加入全局数组windowsArr
191             windowsArr.push(infoWindow);
192             //为了方便使用mar,所以写个内部方法。
193             var aa = function (e) { 
194                 infoWindow.open(mapObj, mar.getPosition());
195                 ShowLatLgn(mar.getPosition());
196             };
197             AMap.event.addListener(mar, "click", aa);
198             AMap.event.addListener(mar, "dragend", MarkerDragendEventHandler);
199         }
200         function MarkerDragendEventHandler(mapsEvent) {
201             ShowLatLgn(mapsEvent.lnglat);
202         }
203         function TipContents(type, address, tel) {  //窗体内容  
204             if (type == "" || type == "undefined" || type == null || type == " undefined" || typeof type == "undefined") {
205                 type = "暂无";
206             }
207             if (address == "" || address == "undefined" || address == null || address == " undefined" || typeof address == "undefined") {
208                 address = "暂无";
209             }
210             if (tel == "" || tel == "undefined" || tel == null || tel == " undefined" || typeof address == "tel") {
211                 tel = "暂无";
212             }
213             var str = "&nbsp;&nbsp;地址:" + address + "<br />&nbsp;&nbsp;电话:" + tel + " <br />&nbsp;&nbsp;类型:" + type;
214             return str;
215         }
216         /*以上代码实现查询结果展示功能*/
217 
218         //将经纬坐标显示按格式:(经度,纬度)显示在文本框中。
219         function ShowLatLgn(latLng) {
220             var lng = latLng.getLng();
221             var lat = latLng.getLat();
222             //结果保留至小数点后六位
223             document.getElementById('LngLat').value = "(" + lng.toString().substr(0, 10) + "," 
224                                                     + lat.toString().substr(0 , 10) + ")";
225         }
226 
227         //将经纬坐标显示框设置为空
228         function EmptyTxtLngLat() {
229             document.getElementById('LngLat').value = "";
230         }
231     </script>  
232 </head>  
233 <body onload="mapInit();"> 
234     <div> 
235     <b>请输入关键字:</b>
236         <input type="text" id="keyword" name="keyword" value="" style="width: 33%;"/>  
237         <input type="button" value=" 搜 索 " id="btnSearch" onclick="search()" />
238          (经度,纬度):&nbsp;&nbsp;&nbsp;
239         <input type="text" disabled="disabled" id="LngLat" size="20" />
240         <div id="searchTips" name="searchTips" style="overflow: auto; width: 95%; border: 1px solid gray;display: none;">
241         </div>  
242     </div>
243     <!--查询结果-->
244     <div class="searchResults" style="width:200px;float:left;">  
245         <div id="r_title">
246             <b>查询结果:</b>
247         </div>  
248         <div id="result">
249             <br />
250         </div>  
251     </div>  
252     <!--map-->
253     <div id="mainMap" style="float:left;" ></div> 
254 </body>  
255 </html>  
View Code

 

本程序可以实现利用关键字搜索地图功能:

  1. 在搜索框中输入关键字:如 “礼顿酒店”,智能提示下拉列表就会显示出很多匹配的地址,将鼠标移到匹配地址上方单击,就执行搜索,左侧显示备选地址,右侧显示地图并按ABCD标注成点。
  2. 若无智能感应提示或提示无结果(如台湾地区),可以直接输入关键字地址后点击“搜索”。若搜索不到结果,则请尝试:该地址不存在或请更换关键字。
  3. 鼠标单击每一个标记或者搜索栏下方的备选地址栏时,经纬地址就会显示在右边框中。鼠标左键按住标记可以进行拖放,至目标处,新标记的经纬坐标显示在右边框中。格式如:(经度,纬度),均保留至小数点后7位。

注意点:

  1. 若智能感应有提示,最好使用智能感应的内容。这样搜索更准确,也方便。(首次加载网页时智能感应会有延迟,稍等几秒钟即可)
  2. 在搜索全国不唯一的地址时(如:喜来登酒店、格林豪泰酒店)务必在地址前或后加上地区(如:江苏、南京),否则可能会搜索不出来。格式如:“格林豪泰酒店 苏州”。
  3. 台湾地区无智能感应,建议对台湾地区的搜索统一使用格式如:台湾省 喜来登酒店。
  4. 高德地图不能搜索国外。
  5. 搜索有时反应较慢,稍等几秒钟即可。
  6. 高德地图不支持国外!

其实高德地图和谷歌地图API使用差不多,如果国内的话推荐高德,网络更稳定。

posted on 2014-04-04 17:00  nlh774  阅读(1298)  评论(0编辑  收藏  举报