1. 程式人生 > >關於高德地圖api的使用(一)

關於高德地圖api的使用(一)

最近筆者的專案打算新增周邊服務的模組,因此嘗試使用了高德地圖。

先上預覽圖,開啟的時候會自動定位(這裡是使用了瀏覽器ip定位,pc端可能不準)。隨意點選會生成一個藍色的標記,並且自動搜尋附近的美食服務。

初始定位(瀏覽器ip定位)

AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,預設:true
            timeout: 10000,          //超過10秒後停止定位,預設:5s
            buttonPosition:'RB',    //定位按鈕的停靠位置
            buttonOffset: new AMap.Pixel(0, 0),//定位按鈕與設定的停靠位置的偏移量,預設:Pixel(10, 20)
            zoomToAccuracy: true,   //定位成功後是否自動調整地圖視野到定位點

        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition(function(status,result){
            if(status=='complete'){
                onComplete(result)
            }else{
                onError(result)
            }
        });
    });
    //解析定位結果
    function onComplete(data) {
        document.getElementById('status').innerHTML='定位成功'
        var str = [];
        console.log(data);
        str.push('定位結果:' + data.formattedAddress);
        str.push('定位類別:' + data.location_type);
        if(data.accuracy){
             str.push('精度:' + data.accuracy + ' 米');
        }//如為IP精確定位結果則沒有精度資訊
        str.push('是否經過偏移:' + (data.isConverted ? '是' : '否'));
        document.getElementById('result').innerHTML = str.join('<br>');
    }
    //解析定位錯誤資訊
    function onError(data) {
        document.getElementById('status').innerHTML='定位失敗'
        document.getElementById('result').innerHTML = '失敗原因排查資訊:'+data.message;
    }
    var toolBar = new AMap.ToolBar({
        visible: true
    });

點選生成和切換藍色標記

先初始化藍色標記(marker),然後通過使用map.on('click',function())來進行點選動作的監聽,當點選時,將會執行後面的function()方法,因為點選生成和切換事件都是在點選後發生的,所以都需要寫到這個function()裡面。map.add(marker)把藍色標記新增到地圖上,當然這個標記的position是你的初始值。當我們想修改這個position時,可以通過setPosition([xxx,xxx])來進行修改。

var marker = new AMap.Marker({
	    icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
	    position: [116.405467, 39.907761],
	});
map.on('click', function());
map.add(marker);
marker.setPosition([xxx,xxx]);

周邊服務查詢

這是高德地圖提供的poi搜尋型別,共20種:

汽車服務|汽車銷售|汽車維修|摩托車服務|餐飲服務|購物服務|生活服務|體育休閒服務|

醫療保健服務|住宿服務|風景名勝|商務住宅|政府機構及社會團體|科教文化服務|

交通設施服務|金融保險服務|公司企業|道路附屬設施|地名地址資訊|公共設施

想要進行poi搜尋,得先構建查詢類,然後進行初始化,最後通過searchNearBy()進行查詢。

AMap.service(["AMap.PlaceSearch"], function() {
        //構造地點查詢類
    });
var placeSearch = new AMap.PlaceSearch({ 
        type: '餐飲服務', // 興趣點類別
        pageSize: 5, // 單頁顯示結果條數
        pageIndex: 1, // 頁碼
        city: "全國", // 興趣點城市
        citylimit: false,  //是否強制限制在設定的城市內搜尋
        map: map, // 展現結果的地圖例項
        panel: "panel", // 結果列表將在此容器中進行展示。
        autoFitView: false // 是否自動調整地圖視野使繪製的 Marker點都處於視口的可見範圍
	});
var cpoint = [food_position.Lng, food_position.Lat]; //中心點座標
        placeSearch.searchNearBy('', cpoint, 300, function(status, result) {
        });

全部程式碼

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>周邊美食</title>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
   
    <style>
        html,
        body,
        #container {
          width: 100%;
          height: 400px;
        }
        #panel {
            position: relative;
            background-color: white;
            overflow-y: auto;
            width: 90%;
            margin:0 5%;
            box-sizing: border-box;
            box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
        }
        .amap_lib_placeSearch{
        	border: none;
        }
        .info{
        	width: 90%;
        	position: relative;
        	top: 0;
        	right: 0;
        	margin:1rem 5%;
        }
        .amap-geolocation-con .amap-geo{
        	width: 25px;
        	height: 25px;
        }
    </style>
</head>
<body>
<div id="container"></div>
<div class="info">
    <h4 id='status'>正在為你定位</h4><hr>
    <p id='result'></p>
</div>
<div id="panel"></div>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.10&key=您申請的key值&&plugin=AMap.Scale,AMap.OverView,AMap.ToolBar"></script>
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
<script type="text/javascript">
    //初始化地圖物件,載入地圖
    var map = new AMap.Map("container", {
        resizeEnable: true
    });
    AMap.service(["AMap.PlaceSearch"], function() {
        //構造地點查詢類
    });
    AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,預設:true
            timeout: 10000,          //超過10秒後停止定位,預設:5s
            buttonPosition:'RB',    //定位按鈕的停靠位置
            buttonOffset: new AMap.Pixel(0, 0),//定位按鈕與設定的停靠位置的偏移量,預設:Pixel(10, 20)
            zoomToAccuracy: true,   //定位成功後是否自動調整地圖視野到定位點

        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition(function(status,result){
            if(status=='complete'){
                onComplete(result)
            }else{
                onError(result)
            }
        });
    });
    //解析定位結果
    function onComplete(data) {
        document.getElementById('status').innerHTML='定位成功'
        var str = [];
        console.log(data);
        str.push('定位結果:' + data.formattedAddress);
        str.push('定位類別:' + data.location_type);
        if(data.accuracy){
             str.push('精度:' + data.accuracy + ' 米');
        }//如為IP精確定位結果則沒有精度資訊
        str.push('是否經過偏移:' + (data.isConverted ? '是' : '否'));
        document.getElementById('result').innerHTML = str.join('<br>');
    }
    //解析定位錯誤資訊
    function onError(data) {
        document.getElementById('status').innerHTML='定位失敗'
        document.getElementById('result').innerHTML = '失敗原因排查資訊:'+data.message;
    }
    var toolBar = new AMap.ToolBar({
        visible: true
    });
    var scale = new AMap.Scale({
        visible: true
    });
    var marker = new AMap.Marker({
	    icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
	    position: [116.405467, 39.907761],
	});
    var placeSearch = new AMap.PlaceSearch({ 
        type: '餐飲服務', // 興趣點類別
        pageSize: 5, // 單頁顯示結果條數
        pageIndex: 1, // 頁碼
        city: "全國", // 興趣點城市
        citylimit: false,  //是否強制限制在設定的城市內搜尋
        map: map, // 展現結果的地圖例項
        panel: "panel", // 結果列表將在此容器中進行展示。
        autoFitView: false // 是否自動調整地圖視野使繪製的 Marker點都處於視口的可見範圍
	});
	map.addControl(scale);
	map.addControl(toolBar);
	map.add(marker);
    function food_position(e){
    	var food_position={};
    	food_position.Lng=e.lnglat.getLng();
    	food_position.Lat=e.lnglat.getLat();
       	marker.setPosition([e.lnglat.getLng(), e.lnglat.getLat()]);
    	map.setFitView();
    	map.setZoom(16);
        var cpoint = [food_position.Lng, food_position.Lat]; //中心點座標
        placeSearch.searchNearBy('', cpoint, 300, function(status, result) {
        });
    }
    map.on('click', food_position);
</script>
</body>
</html>