高德地圖 JS API - 根據地名實現標記定位


德地圖 JS API 使用前的准備工作請參考官方網站說明: https://lbs.amap.com/api/javascript-api/guide/abc/prepare

 

根據地名實現地圖標記定位,主要依賴高德地圖的:地理編碼與逆地理編碼。下面來看具體的實現代碼:

1. HTML (地圖容器)

<div class="map-container" id="container"></div>

 

2. JAVASCRIPT

function markLocation(mapId, address) {
    AMap.plugin('AMap.Geocoder', function() {
        var geocoder = new AMap.Geocoder();            
        geocoder.getLocation(address, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {

                // 經緯度                      
                var lng = result.geocodes[0].location.lng;
                var lat = result.geocodes[0].location.lat;

                // 地圖實例
                var map = new AMap.Map(mapId, {
                    resizeEnable: true, // 允許縮放
                    center: [lng, lat], // 設置地圖的中心點
                    zoom: 15        // 設置地圖的縮放級別,0 - 20
                });
                        
                // 添加標記
                var marker = new AMap.Marker({
                    map: map,
                    position: new AMap.LngLat(lng, lat),   // 經緯度
                });
            } else {
                console.log('定位失敗!');
            }
        });
    });
}

 

方法寫好了,調用很簡單了:

// 傳入地圖容器ID 和 地名
markLocation('container', '湖北省武漢市');

 

3. 效果圖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM