高德地圖API基礎使用
- 高德地圖API體驗
-
- 申請Key
- 初體驗
- 添加插件
- 點選事件傳回位址值
- 兩點之間擷取駕車導航路線
高德地圖API體驗
申請Key
- 申請高德地圖賬号
- 登入後,應用管理下建立自己的應用
- 在應用中建立自己的key值,選擇web端API
初體驗
完成以下操作即可顯示簡單的地圖控件。
<!-- 為地圖顯示建立一個div -->
<div id="container"></div>
<!-- 異步加載地圖腳本 -->
<script type="text/javascript">
window.init = function(){
var map = new AMap.Map('container', {
center:[117.000923,36.675807], //定義打開地圖時顯示的坐标
zoom:11
});
}
</script>
<script src="https://webapi.amap.com/maps?v=1.4.15&key=您申請的key值&callback=init"></script>
添加插件
本次開發用到了位置坐标、車輛路線規劃等功能,是以加了以下插件。視情況而定。
//添加元件
AMap.plugin(['AMap.ToolBar','AMap.Geolocation','AMap.Geocoder','AMap.Driving'],function(){//異步加載插件
var toolbar = new AMap.ToolBar(); //工具條縮放
var Geolocation = new AMap.Geolocation(); //定位
//加載地圖導航元件
var driving = new AMap.Driving({
map: map
});
map.addControl(toolbar);
map.addControl(Geolocation);
//map.on('click', showInfoClick);//地圖點選事件
});
點選事件傳回位址值
在官方API中提供了點選事件傳回地點火星坐标的方法,擷取其坐标之後在轉換為地點位置名稱。
map.on('click', showInfoClick);//地圖點選事件
//點選事件,傳回坐标值
function showInfoClick(e){
lnglatXY = [e.lnglat.getLng(),e.lnglat.getLat()]; //已知點坐标
regeocoder(lnglatXY);
}
//根據坐标傳回位址
function regeocoder(loc){
var geocoder = new AMap.Geocoder({
radius: 1000,
extensions: "all"
});
geocoder.getAddress(loc, function(status, result) {
if (status === 'complete' && result.info === 'OK') {
geocoder_CallBack(result);
}
});
map.setFitView();
}
//獲得位址描述資訊
function geocoder_CallBack(data) {
var address = data.regeocode.formattedAddress; //傳回位址描述
console.dir("點選位置的位址資訊是" + address);
}
兩點之間擷取駕車導航路線
高德地圖API中提供了兩點之間傳回駕車路徑的方法。因為其傳回的坐标是名稱[經,緯]格式,故計算路徑時應該為起始點[經,緯] – 終止點[經,緯]
關于driving.clear();方法:如果不适用clear()方法,在改變了原路線的基礎上,其舊路線不會被消除。
關于傳回值:
//獲得駕車路線
function getDrivingMap(startXY,endXY){
//清除上次規劃路線
if(driving){
driving.clear();
}
driving.search(new AMap.LngLat(startXY[0], startXY[1]), new AMap.LngLat(endXY[0], endXY[1]), function(status, result) {
// result 即是對應的駕車導航資訊,相關資料結構文檔請參考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
if (status === 'complete') {
//成功
//計算時間
var time = 0;//秒
for(var i = 0; i < result.routes.length ; i++){
time += result.routes[i].time;
}
time = (Math.round(time/60/60*100)/100);
$("#times").val(time);
//計算距離
var distance = 0;
for(var i = 0; i < result.routes.length ; i++){
distance += result.routes[i].distance;
}
$("#distance").val(Math.round(distance/1000*100)/100);
} else {
//失敗
console.dir("路線規劃失敗!")
}
});
}