1.导入高德地图的js
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=89d13a19a11c8c3e920cbb68732ec9ba"></script>
2.参照高德地图的插件
http://lbs.amap.com/api/javascript-api/reference/search_plugin/#m_AMap.DistrictSearch
3.例子:
0. 全局变量
var mapObj
var poiArr //地区列表
1. 注册地图
<div id="iCenter" style="width: 0;height: 0;overflow: hidden;"></div>
<input type="text" placeholder="您在哪儿上车" id="searchPlace"/>
mapObj = new AMap.Map('iCenter');
document.getElementById("searchPlace").addEventListener("input",falsePlace,false);
2.定位当前城市
function showCityInfo() { //IP定位
//加载IP定位插件
mapObj.plugin(["AMap.CitySearch"], function() {
//实例化城市查询类
var citysearch = new AMap.CitySearch();
//自动获取用户IP,返回当前城市
citysearch.getLocalCity();
AMap.event.addListener(citysearch, "complete", function(result){
if(result && result.city && result.bounds) {
var cityinfo = result.city;
$("#city").html(cityinfo)
cityName=cityinfo
console.log("定位城市:"+cityName)
showPalce()
}
else {
$("#city").html(result.info)
cityName=result.info
showPalce()
}
});
AMap.event.addListener(citysearch, "error", function(result){alert(result.info);});
});
}
3.定位城市之后改变区域
function showPalce(){
console.log("改变城市后准备显示区域")
var panel=$("#center")
mapObj.plugin(["AMap.PlaceSearch"],function(){
placesearch=new AMap.PlaceSearch({
city:cityName,
citylimit:true,
panel:"iCenter",
extensions:"all",
pageSize:20
});
placesearch.search()
AMap.event.addListener(placesearch, "complete", function(result){
console.log("改变城市后成功显示区域")
poiArr=result.poiList.pois
console.log(poiArr.length)
for(i=0;i<poiArr.length;i++){
console.log(poiArr[i].id+"+"+poiArr[i].name+"+"+poiArr[i].address+"+"+poiArr[i].citycode)
}
flashCenter()
});
AMap.event.addListener(placesearch, "error", function(result){alert(result.info);});
})
}
4.刷新地区
function falsePlace(){
console.log("刷新地区")
var place=$("#searchPlace").val()
placesearch.search(place)
flashCenter()
}
5.刷新center
function flashCenter(){
$("#center > ul").empty()
var place=$(".place").clone(true);
console.log(poiArr.length);
for(i=0;i<poiArr.length;i++){
place.children(".big-title").html(poiArr[i].name)
place.children(".small-tip").html(poiArr[i].address)
$("#center > ul").append(place)
place.css("display","block")
place=place.clone(true)
}
}
6. 计算两点间的距离
function returnTotalDistance(){
var distances=0
console.log("计算两点间距离开始")
mapObj.plugin(["AMap.Driving"],function(){
driving=new AMap.Driving({
policy:AMap.DrivingPolicy.LEAST_DISTANCE,
extensions:"all"
});
driving.search(startPlace.location,endPlace.location,function(status,result){
if(status=="complete"){
console.log("计算两点间的距离")
console.log(result.routes.length)
for(i=0;i<result.routes.length;i++){
console.log(result.routes[i].distance)
distances=distances+result.routes[i].distance
}
console.log(distances)
totalDistance=distances;
console.log("最终总距离"+totalDistance)
flashMoney()
}
if(status=="error"){
alert(result.info)
}
})
})
}