Sam*_*tch 1 javascript google-maps
我正在尝试制作基于地图的应用程序,但我遇到了一些困难.我一直在使用的原始代码为每个标记添加了一个单独的InfoWindow,但我想使用单个InfoWindow来获取它,我可以动态设置内容.
但是,我似乎仍然对JavaScript的行为有点模糊,因为每次点击任何标记时,InfoWindow会弹出最后一个标记,并且警报会指示最后一个条目的ID locations.
短片,问题突出显示:
function plotLocations(my_locations) {
locations = my_locations;
for(var i=0; i<locations.length; i++) {
var pos = new google.maps.LatLng(locations[i].loc_lat, locations[i].loc_lng);
var icon = new google.maps.MarkerImage(
"http://goo.gl/TQpwU",
new google.maps.Size(20,32),
new google.maps.Point(0,0),
new google.maps.Point(0,32)
);
var marker = new google.maps.Marker({
map: map,
position: pos,
animation: google.maps.Animation.DROP,
icon: icon
});
// ! -- trouble right here -- ! //
google.maps.event.addListener(marker, 'click', function() {
setPopInfo(pos, i);
});
// ! -- ------------------ -- ! //
}
}
function setPopInfo(pos, index) {
pop_info.setPosition(pos);
pop_info.open(map);
window.alert(pos+"::"+index);
}
Run Code Online (Sandbox Code Playgroud)
我剩下的大部分代码:
var map;
var mapBounds;
var locations;
var pop_info;
$(document).ready(init);
function init() {
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
pop_info = new google.maps.InfoWindow({
content: "I'm not populated!",
size: new google.maps.Size(100,25)
});
google.maps.event.addListener(map, 'bounds_changed', function() {
queryLocations(map.getBounds());
});
prepareGeolocation();
doGeolocation();
}
function queryLocations(bounds) {
jQuery.ajax({
url: 'http://mydomain.com/myapp/test2.php',
data: bounds.toString(),
dataType: 'json',
success: addLocations
});
}
function addLocations(new_locations) {
document.getElementById('footer').innerHTML = new_locations;
plotLocations(new_locations);
}
Run Code Online (Sandbox Code Playgroud)
我对单个InfoWindow的推理是,一旦创建了几百个Markers和InfoWindows,性能可能会急转直下.我正在努力做到可行/可取吗?
出现此问题是因为您在循环内定义了事件侦听器回调函数.闭包动态地引用它们的上下文,而不是在定义时绑定到数据的副本,因此您有效地创建了locations.length多个函数,这些函数都绑定到相同的值marker,pos并且i,这些是它们在循环终止.
为了解决这个问题,你可以创建一个addListener在循环体外调用的函数,如下所示:
function plotLocations (my_locations) {
locations = my_locations;
for(var i=0; i<locations.length; i++) {
var pos = new google.maps.LatLng(locations[i].loc_lat, locations[i].loc_lng);
var icon = new google.maps.MarkerImage(
"http://goo.gl/TQpwU",
new google.maps.Size(20,32),
new google.maps.Point(0,0),
new google.maps.Point(0,32)
);
var marker = new google.maps.Marker({
map: map,
position: pos,
animation: google.maps.Animation.DROP,
icon: icon
});
bindEvent(marker, pos, i);
}
}
function bindEvent (marker, pos, i) {
google.maps.event.addListener(marker, 'click', function() {
setPopInfo(pos, i);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
662 次 |
| 最近记录: |