【发布时间】:2017-12-22 15:40:35
【问题描述】:
我遇到了 Google Maps API 标记的问题,
这里是 ajax succes 函数的代码(map 是包含此代码的函数的参数):
success: function(data) {
var tmpmap = map; //Without this the map wont let me add markers
ris = JSON.parse(data); //Parsing to json
for (var i = 0; i < ris.length - 1; i++) {//Here is the for
var id = ris[i].id_sede; //Here i get the id from the json
var marker = new google.maps.Marker({ //Here i create the marker
map: tmpmap,
mid: id, //And there is where i got that problem.
position: {
lat: parseFloat(ris[i].latitude),
lng: parseFloat(ris[i].longitude)
}
});
ajax 收集的数据是一个普通的 SQL 查询,其中包含纬度、经度、ID 和一些额外的信息。
所以问题是:在for的每个循环中,之前创建的每个标记都假定当前“mid”(地图ID)的值。
TL;DR 我有 4 个标记,在循环结束时,中间 1 2 3 和 4 所有标记的中间值都是 4,而不是 1 2 3 和 4。
最后一个问题是:如何防止这种行为?我是否正确创建标记?为什么当我改变一个标记的值时,所有其他标记都做同样的事情?
【问题讨论】: