Gaode map API, click on the map marker to get the information in the custom marker (Marker)
Adding custom icons and custom window markers through AutoNavi Maps JS Web has been able to add custom markers to the map normally.
This article talks about how to get the information you need from the custom markers when you click on the markers, and how to preset them. some information about yourself.
1. Demand
I have defined such a map and added these markers, now I need to get the corresponding item id when I click on these markers
2. Explore and solve
I couldn't find an official example, so I solved it myself.
1. How to add markers to the map
The process of adding tags is as follows (specifically in the link mentioned above, so I won’t repeat it):
- The new
AMap.Marker
map marker object - Add these
Markers[]
to the already built map object - The markers will now appear on the map as normal.
2. Add a click event to the marker
In the above step 2, you can add Marker
a click event to it, which is the same as the normal dom
operation. Its format is as follows:
I define a custom marker here, and add data-projectid
a parameter named to its html structure
// 1. 新建 Marker
let marker = new AMap.Marker({
position: [
Number(projectItem.prjinfo.location.longitude),
Number(projectItem.prjinfo.location.latitude),
],
offset: new AMap.Pixel(0,-20),
content: `
<div data-projectid="${
projectItem.id}" class="marker ${
projectItem.status === 'offline'? 'offline': ''}">
<div class="title">${
projectItem.prjinfo.projectname}</div>
<div class="note">位置: ${
projectItem.prjinfo.location.detail}</div>
<div class="note">设备: ${
projectItem.prjinfo.deviceCnt} 个</div>
<div class="note">状态: ${
projectItem.status === 'offline'? '离线': '在线'}</div>
</div>`,}]
// 2. 给这个 Marker 添加点击事件
marker.on('click', mapEvent => {
console.log(mapEvent.target.dom.getElementsByClassName('marker')[0].getAttribute('data-projectid'))
console.log(mapEvent.target)
})
// 3. 添加到地图中
map.add(marker)
3. Get the custom parameter value in the custom tag
Here we need to get the value defined in advance above data-projectid
.
The answer is all mapEvent
on , let's take a look at mapEvent.target
what's in :
What we need is mapEvent.target.dom
the content in , which is a dom object:
After obtaining it, you can use the operation method of dom to align and get the value:
If you don’t know much about the operation method of dom, it is best to find relevant information and look at it. The common ones are:
getElementById()
getElementByClassName()
getElementByTagName()
Like the following, we get its data-projectid
attribute value
mapEvent.target.dom.getElementsByClassName('marker')[0].getAttribute('data-projectid'))
4. Do follow-up operations
After getting the value, you can do whatever you want. For example, use this value to jump to the corresponding project, use this value to obtain the information of the corresponding project, etc.