高德地圖jsAPI,定位和選擇位置

一、前端頁面

 
#container {
        width: 700px;
        height: 311px;
    }

<div id="container">
這裏是地圖控件的容器
</div>

二、js

首先引入api

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.12&key=申請的開發者密匙&plugin=AMap.Geocoder"></script>

接着在script標籤中就可以調用了:

//地圖初始位置,可以在頁面初始化時傳入經緯度,也可以ajax獲取,不過由於地圖初始化較慢,需要考慮同步
var lon = $('#longitude').val()
var lat = $('#latitude').val();
var map;
if (lon > 0) {//初始化到已有地點
    map = new AMap.Map('container', {
        zoom: 20,
        resizeEnable: true,
        center: [lon, lat],
        viewMode: '3D'
    });
} else {//初始化到默認地點
    map = new AMap.Map('container', {
        zoom: 12,
        resizeEnable: true,
        viewMode: '3D'
    });
}
//此插件用來顯示當前位置,可在引入API時一同引入
map.plugin('AMap.Geolocation', function () {
    var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 10000,
        buttonOffset: new AMap.Pixel(10, 20),
        zoomToAccuracy: true,
        buttonPosition: 'RB'
    });
    map.center = geolocation;
    map.addControl(geolocation);//地圖控件右下角顯示當前位置
});

var geocoder, marker;
if (!marker) {
    marker = new AMap.Marker();
    map.add(marker);
}

var lnglat;
//地圖點擊時,獲取點擊地經緯度
map.on('click', function (e) {
    lnglat = e.lnglat;
    regeoCode();
})
function regeoCode() {
    if (!geocoder) {
        geocoder = new AMap.Geocoder();
    }

    if (!marker) {
        marker = new AMap.Marker();
        map.add(marker);
    }
    marker.setPosition(lnglat);//設置標記的位置
    geocoder.getAddress(lnglat, function (status, result) {
        if (status === 'complete' && result.regeocode) {
            var address = result.regeocode.formattedAddress;
            //$('#address').val(address);//點擊地名稱
            //$('#longitude').val(lnglat.lng);//經緯度
            //$('#latitude').val(lnglat.lat);
        }
    });
    marker.setMap(map);//在地圖上顯示一個標記
}
// marker.setPosition([lon, lat]);

三、效果

點擊右下角時會定位到當前位置(網絡位置),點擊地圖的其他地方,藍色標記會移動並獲取當地名稱和經緯度。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章