对象内部表达式 - Javascript
从我读到的内容来看,我认为这是不可能的,但是是否可以检查以下代码中的地图标记是否为空?我读过一些有关原型的内容,但我不确定这是否是我需要使用的。这是代码:
this.currentLocation = function(latitude, longitude) {
if (loc_marker != null) {
loc_marker.setPosition(new google.maps.LatLng(latitude, longitude);
}
else {
var loc_marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
title: "Here"
});
loc_marker.setMap(map);
}
};
每次位置发生变化时,我都会尝试移动 Google 地图上的标记。我想检查是否已设置标记,如果已设置,那么我只需使用 setPosition(); 更改位置即可
如果您有任何建议,我将非常感激!
I don't think this is possible from what I read, but is there away to check if my map marker is null in the following code? I read something about prototypes, but I'm not sure if that's what I need to use. Here is the code:
this.currentLocation = function(latitude, longitude) {
if (loc_marker != null) {
loc_marker.setPosition(new google.maps.LatLng(latitude, longitude);
}
else {
var loc_marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
title: "Here"
});
loc_marker.setMap(map);
}
};
I'm trying to move a marker on a Google Map each time the location changes. I want to check to see if a marker has been set, and if it has then I'll just change the position using setPosition();
If you have any suggestions I'd really appreciate it!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下所有内容都将满足您的要求...
也就是说, loc_marker 实际定义在哪里?它看起来“就像”你试图在 else 块中定义它(尽管 JavaScript 不能那样工作< /a>)。
除了声明
loc_marker
的位置之外,您拥有的代码应该可以正常工作。希望这有帮助,
皮特
All of the following will do what you're looking for...
That said, where is
loc_marker
actually defined? It looks "like" you're trying to define it in the else block (although JavaScript doesn't work that way).Save for where you're declaring
loc_marker
, the code you have should work fine.Hope this helps,
Pete
您必须将 loc_marker 设为“全局”变量,即每次调用函数时该变量都指向同一个对象。在上面的代码中,您只会在函数范围内创建另一个局部变量。尝试类似的方法:
You will have to make
loc_marker
a "global" variable, i.e. that the variable points to the same object each time the function is called. In your code above, you only will create another local variable in the scope of the function. Try something like:而不是
尝试
instead of
try