对接高德地图实例、获取当前城市、根据输入提示城市
这是一个对接高德地图获取当前城市和根据输入提示城市的小例子,如有不足或困惑,请在评论区留言。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>高德地图获取当前城市&输入提示</title>
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.4.15&key=您的key&plugin=AMap.CitySearch,AMap.Autocomplete,AMap.PlaceSearch"></script>
<link rel="stylesheet" href="https://cache.amap.com/lbs/static/main1119.css"/>
<script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
<style>
#amapInp{
position: fixed;
right: 0;
margin: 10px;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="amapInp">
<input id="tipinput"/>
</div>
<script type="text/javascript">
//地图加载
var map = new AMap.Map("container", {
resizeEnable: true
});
//异步方法
Promise.prototype.finally = function (callback) {
var P = this.constructor;
return this.then(
function(value){
P.resolve(callback()).then(function(){
return value
})
},
function(reason){
P.resolve(callback()).then(function(){
throw reason
})
}
);
};
//获取用户所在城市信息
function showCityInfo() {
return new Promise(function (resolve, reject) {
var res;
//实例化城市查询类
var citysearch = new AMap.CitySearch();
//自动获取用户IP,返回当前城市
citysearch.getLocalCity(function(status, result) {
if (status === 'complete' && result.info === 'OK') {
if (result && result.city && result.bounds) {
var cityinfo = result.city;
var citybounds = result.bounds;
res = cityinfo;
}
} else {
res = result.info;
}
resolve(res);
});
});
}
showCityInfo().then(function(res){
console.log('当前城市->',res);
//输入提示
var autoOptions = {
city: res,
input: "tipinput"
};
var auto = new AMap.Autocomplete(autoOptions);
var placeSearch = new AMap.PlaceSearch({
map: map
}); //构造地点查询类
//构造地点查询类
AMap.event.addListener(auto, "select", select);//注册监听,当选中某条记录时会触发
function select(e) {
console.log(e.poi.district,e.poi.address,e.poi.name);
placeSearch.setCity(e.poi.adcode);
placeSearch.search(e.poi.name); //关键字查询查询
}
});
</script>
</body>
</html>


