我正在尝试动态附加hrefs,点击后,将Google地图平移到指定的坐标。下面的代码成功创建了平移地图的href链接 - 但它会一直平移到最近创建的圆的位置。
我添加了闭包panToCircle,希望能保留封闭的IIFE中的当前坐标,但没有这样的运气。您认为我最好的策略是什么?万分感谢!
注意:这些都是从异步回调中链接的,每次响应来自服务器时都会创建一个循环。
var text = 'Hello World!';
// Hoisting the panToCircle up here, as Chrome was giving me undefined ref errors when initializing it in linkToCircle.
var panToCircle = function(){};
var rgb = [100,100,100];
createCircle();
function createCircle(){
var color = 'RGB(' + rgb.toString() + ')';
var myCircle = initCircle();
linkToCircle();
function linkToCircle(){
var a = document.createElement('a');
a.innerHTML = text + "<br><br>";
a.style.color = color;
panToCircle = function(){
// Defining center in here, as putting a center in as an argument to the href function reclasses the center as a string, not a latLng
var center = myCircle.getCenter();
(function panNow(cen){
map.panTo(cen);
})(center);
}
a.href = 'javascript:panToCircle();'
document.getElementById('text-div').appendChild(a);
}
}
答案 0 :(得分:0)
酷,一个非常简单的修复工作,只需退后一步并考虑其他选项。我从当前坐标格式化了一个字符串,并将其连接到href值。
function linkToCircle(){
var a = document.createElement('a');
a.innerHTML = text + "<br><br>";
a.style.color = color;
panToCircle = function(latLng){
alert(latLng)
var cen = {'lat': Number(latLng[0]), 'lng': Number(latLng[1])};
map.panTo(cen);
}
// Just had to do an eval-ish thing to get it to take the current coordinates by
// formatting the string correctly, as an array. I had tried something similar
// before, but it was rejecting the arguments as a comma-separated list.
var centerString = center.lat.toString() + ',' + center.lng.toString();
a.href = 'javascript:panToCircle([' + centerString + ']);'
document.getElementById('text-div').appendChild(a);
}
请随时回答一下为什么我的关闭尝试失败的原因。关闭对我来说是新的(我一般都是js的新手),很想了解更多。将接受一个解释第一篇文章的闭包元素的答案。谢谢!