我试图在画布上画画,但我绘制的点最终位于错误的位置。我知道这是与循环相关的东西(很可能是变量范围和事件序列),因为当我一次绘制一个数据点时,它们会显示在正确的位置。一旦我循环遍历一个多个元素的数组,这些点就不会在正确的位置结束(我在谷歌地图上绘制它们 - 是的,我已经使用了他们的javascript api但是我要去做一些比他们的api更自定义的东西。但是使用他们的api来映射点是我如何确认我的点在一次完成一个时在正确的位置绘制,但当我循环遍历数组时最终在错误的位置)
map.setCenter(new google.maps.LatLng(data[0].location.lat, data[0].location.long));
map.setZoom(15);
var bounds = map.getBounds();
var topLeft = bounds.getNorthEast();
var bottomRight = bounds.getSouthWest();
var left = topLeft.lat();
var top = topLeft.lng();
var right = bottomRight.lat();
var bottom = bottomRight.lng();
var height = Math.abs(top - bottom);
var width = Math.abs(left - right);
canvas = $('#mapCanvas').get(0);
var canvasHeight = canvas.height;
var canvasWidth = canvas.width;
context = canvas.getContext('2d');
var radius = 10;
var fromTop;
var fromLeft;
var ratioTop;
var ratioLeft;
var centerX;
var centerY;
_.each(data, function(point) {
var latLng = new google.maps.LatLng(point.location.lat, point.location.long);
if (bounds.contains(latLng)) { // this point lies in the map, plot it on the canvas!
// calculate distance from top left
fromTop = Math.abs(top - point.location.long);
fromLeft = Math.abs(left - point.location.lat);
ratioTop = fromTop / height;
ratioLeft = fromLeft / width;
centerX = Math.floor(ratioLeft * canvasWidth);
centerY = Math.floor(ratioTop * canvasHeight);
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.closePath();
}
});
注意 - 数据数组包含如下对象:
{ _id: 5362a54a038a09d66ac9b36d,
location: { lat: 46.368619, long: -109.027793 } }
以下是问题的示意图:在画布上绘制绿点,使用谷歌的api绘制黄色和紫色点。请注意,绘制的第一个点与正确的位置重叠。另外,如前所述,如果我只是单独绘制第三个点,或者单独绘制任何一个点,那么它们就会显示在正确的位置。
我还整理了jsFiddle
答案 0 :(得分:1)
在读这个答案之前,请坐下来,不要把头撞在墙上! :-)
您的代码非常好,您只是认为纬度与' x'匹配。坐标和经度与' y'坐标。
但实际上反过来说是对的:如果有疑问,再看一下定义。
如果你看看你的错误'结果,它只是正确的结果旋转和缩放。
所以只需1)在这里和那里经纬度交换,2)采用经度的对称,你与谷歌的结果完全匹配:
http://jsfiddle.net/gamealchemist/68Gy4/2/
// during the init :
var bounds = map.getBounds();
var topLeft = bounds.getNorthEast();
var bottomRight = bounds.getSouthWest();
var left = topLeft.lng();
var top = topLeft.lat();
var right = bottomRight.lng();
var bottom = bottomRight.lat();
var height = Math.abs(top - bottom);
var width = Math.abs(left - right);
// and in your each loop :
var fromTop = Math.abs(top - point.location.lat);
var fromLeft = Math.abs(left - point.location.long);
var ratioTop = fromTop / height;
var ratioLeft = fromLeft / width;
var centerX = canvasWidth - Math.floor(ratioLeft * canvasWidth);
var centerY = Math.floor(ratioTop * canvasHeight);
完全可以的结果: