google map的GEvent.addListener使用心得

原代码是这样的

parent.map.clearOverlays();//不能执行已释放的Script代码
//为所有标记创建指定阴影、图标尺寸灯的基础图标
var baseIcon = new GIcon();
baseIcon.shadow = "http://www.google.cn/mapfiles/shadow50.png";
//baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(0, 0);

for (var i = 0; i < json.length; i++) {
var myicon = new GIcon(baseIcon);
myicon.image = "/webtrack/img/car/car";
//根据方向来确定显示哪一个图标
var direct = json[i].direction;
if (direct - 0.0 > -22.5 && direct - 0.0 < 22.5) {
myicon.image += "0";
}
else if (direct - 45 > -22.5 && direct - 45 < 22.5) {
myicon.image += "45";
}
else if (direct - 90 > -22.5 && direct - 90 < 22.5) {
myicon.image += "90";
}
else if (direct - 135 > -22.5 && direct - 135 < 22.5) {
myicon.image += "135";
}
else if (direct - 180 > -22.5 && direct - 180 < 22.5) {
myicon.image += "180";
}
else if (direct - 225 > -22.5 && direct - 225 < 22.5) {
myicon.image += "225";
}
else if (direct - 270 > -22.5 && direct - 270 < 22.5) {
myicon.image += "270";
}
else if (direct - 315 > -22.5 && direct - 315 < 22.5) {
myicon.image += "315";
}
if (json[i].speed - 10.0 < 0) {
myicon.image += "_S.gif";
}
else {
myicon.image += ".gif";
}
//设置 GMarkerOptions 对象 GMarker 标记地图上的位置。它实现 GOverlay 接口,因此可使用 GMap2.addOverlay() 方法添加到地图中。
markerOptions = { icon:myicon };
//初始化一个,GLatLng 是以经度和纬度表示的地理坐标点。
var latlng = new GLatLng(json[i].latitude, json[i].longitude);
var pointMarker = new GMarker(latlng, markerOptions);
parent.map.addOverlay(pointMarker);
//注册点击事件
var content = "PlateNo.:" + json[i].vehicle.plateNo + "<br>time:" + json[i].orientationTime
+ "<br>location:" + json[i].location + "<br>speed:" + json[i].speed + " km/h";
GEvent.addListener(pointMarker, "click", function(){
parent.map.openInfoWindow(latlng, content);
});
}

执行时,发现画在地图上的任何一个图标,弹出的infoWindow都是完全相同的,且显示的位置也一样。这就说最后一句代码parent.map.openInfoWindow(latlng, content);的参数是一样的。分析可知,因为注册监听器是异步的,故必须把注册监听器的操作独立放进一个函数中,否则,latlng, content这两个参数将会永远是最新的同一个值。

修改方法如下:

//注意:我这里把注册监听器操作单独写在了一个函数里。
function addListener(pointMarker,latlng,content) {
GEvent.addListener(pointMarker, "click", function(){
parent.map.openInfoWindow(latlng, content);
});
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值