前端时间在项目中遇到了需要使用高德地址输入提示的需求,需要同时获取地址名称和相应的经纬度信息,经过查阅高德api文档,发现高德有一个默认带界面的输入提示功能,开发起来非常方便,但是在使用一段时间后发现,在输入一个类型地址,例如:中国银行,麦当劳等一种品牌或类型的地址时,高德不能返回具体的经纬度信息,这导致表单中的经纬度信息不能正常获取,后来继续查阅高德api,发现它还支持另外一种不带界面的提示功能,就不会出现在上面提到的获取不到经纬度数据的问题了;以上作为此文的背景吧,使用typeahead.js可以低成本的实现类似高德输入提示的功能又不会出现获取不到经纬度的情况;一般场景使用typeahead.js从服务端获取数据的场景我就不再多说了,可以直接参考官方文档:https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#jquerytypeaheadoptions-datasets
我想在这里说的是将高德API和typeahead.js集成使用的场景;
必要条件,引入高德api和typeahead的js文件
以下为具体代码
<script type="text/javascript"> /** * 添加地图事件 * @param comp */ function addAMapListener(comp){ var placeSearch = new AMap.PlaceSearch({ city:'城市code',//具体请见高德官网 extensions:'all'//输入提示返回所有相关信息 }); $('#' + comp).typeahead({ highlight: true, hint:false }, { limit: 10,//提示数量 displayKey: 'suggest',//返回json数据中展示的属性 source: function(query, syncResults, async) { placeSearch.search(query, function(status, result){ if("complete" != status){ return ; }//这里调用高德的api var pois = result.poiList.pois; // console.log(JSON.stringify(pois)); formatSuggest(pois); async(pois);//将数据异步展示 }); } }); //这里绑定选中后的事件 $('#' + comp).bind('typeahead:select', function(ev, suggestion) { var curTr = $(ev.target).closest('div'); //curTr.find('.input-address-amaps-juma').val(suggestion.name); $('#' + comp).typeahead('val', suggestion.name); curTr.find('.input-address-amaps-regionCode').val(""); curTr.find('.input-address-amaps-detail').val(suggestion.pname + suggestion.cityname + suggestion.adname + suggestion.address); curTr.find('.input-address-amaps-coordinates').val(suggestion.location.lng + "," + suggestion.location.lat); }); //避免遮挡 $('.tt-input').css('z-index', 1); } //格式化展示内容 function formatSuggest(data){ if(data == null || data.length <= 0) return ; for(var i = 0;i < data.length; i++){ data[i].suggest = data[i].name + '-' + data[i].address; } } </script>
以上代码可以实现类似高德的地址提示效果,并可以解决没有经纬度的问题;
另外,在项目中还遇到了因为网速问题导致高德插件没有加载完成,导致业务代码调用报错的问题,高德提供了一个初始化回调,可以保证在插件初始化完成之后在调用业务代码,以下是高德给出的代码
<script src="http://webapi.amap.com/maps?v=1.3&key=您申请的key值&callback=init"></script>
<script type="text/javascript">
window.init = function(){
var map = new AMap.Map('container', { center:[117.000923,36.675807], zoom:11 });
}
</script>
效果如下图