高德地圖新增Marker點標記
阿新 • • 發佈:2019-01-26
示例程式碼部分:
<!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="http://cache.amap.com/lbs/static/main1119.css"/>
<style>
.marker {
color: #ff6600;
padding: 4px 10px;
border: 1px solid #fff;
white-space: nowrap;
font-size: 12px;
font-family: "";
background-color : #0066ff;
}
</style>
<script src="http://webapi.amap.com/maps?v=1.3&key=您申請的key值"></script>
<script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
</head>
<body>
<div id="container"></div>
<div class ="button-group">
<input type="button" class="button" value="新增點標記覆蓋物" id="addMarker"/>
<input type="button" class="button" value="更新點標記覆蓋物" id="updateMarker"/>
<input type="button" class="button" value="刪除點標記覆蓋物" id="clearMarker"/>
</div>
<script>
var marker, map = new AMap.Map("container", {
resizeEnable: true,
center: [104.747402,31.46131],
zoom: 13
});
AMap.event.addDomListener(document.getElementById('addMarker'), 'click', function() {
addMarker();
}, false);
AMap.event.addDomListener(document.getElementById('updateMarker'), 'click', function() {
marker && updateMarker();
}, false);
AMap.event.addDomListener(document.getElementById('clearMarker'), 'click', function() {
if (marker) {
marker.setMap(null);
marker = null;
}
}, false);
// 例項化點標記
function addMarker() {
if (marker) {
return;
}
marker = new AMap.Marker({
icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
position: [104.747402,31.46131]
});
marker.setMap(map);
}
function updateMarker() {
// 自定義點標記內容
var markerContent = document.createElement("div");
// 點標記中的圖示
var markerImg = document.createElement("img");
markerImg.className = "markerlnglat";
markerImg.src = "http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png";
markerContent.appendChild(markerImg);
// 點標記中的文字
var markerSpan = document.createElement("span");
markerSpan.className = 'marker';
markerSpan.innerHTML = "Hi,我換新裝備啦!";
markerContent.appendChild(markerSpan);
marker.setContent(markerContent); //更新點標記內容
marker.setPosition([104.747402,31.46131]); //更新點標記位置
}
</script>
</body>
</html>
- 程式碼片分析:
核心部分,如何新增一個點?
實現基本功能的程式碼:
//這裡是設定地圖中心點,比如這裡選了一個綿陽為中心的座標
var marker, map = new AMap.Map("container", {
resizeEnable: true,
center: [104.747402,31.46131],
zoom: 13
});
window.onload = function(){
addMarker();
}
// 例項化點標記
function addMarker() {
if (marker) {
return;
}
marker = new AMap.Marker({
icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
position: [104.747402,31.46131]//在這裡設定需要打點的座標
});
marker.setMap(map);
}
講獲取的店座標拷貝到示例程式碼此處:
儲存,執行,地圖上出現Marker點