德地圖 JS API 使用前的准備工作請參考官方網站說明: https://lbs.amap.com/api/javascript-api/guide/abc/prepare
示例:https://lbs.amap.com/demo-center/js-api
根據地名實現地圖標記定位,主要依賴高德地圖的:地理編碼與逆地理編碼。下面來看具體的實現代碼:
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', '湖北省武漢市');
本文轉載自https://www.cnblogs.com/similar/archive/2018/08/01/9400601.html
