【发布时间】:2011-10-18 16:39:04
【问题描述】:
我在地图中有 2 个 (lat,lng) 标记:p1 和 p2。我需要以 pixels 为单位计算从 p1 到 p2 的多边形的长度。
这是我目前通过获取斜边值的解决方案:
//set global variables
var pixel_coordinates = [];
var overlay;
//create map
map = new google.maps.Map(document.getElementById('map'),myOptions);
//create overlay using this solution http://stackoverflow.com/questions/1538681/how-to-call-fromlatlngtodivpixel-in-google-maps-api-v3
function MyOverlay(options) {
this.setValues(options);
var div = this.div_= document.createElement('div');
div.className = "overlay";
};
MyOverlay.prototype = new google.maps.OverlayView;
MyOverlay.prototype.onAdd = function() {
var pane = this.getPanes().overlayLayer;
pane.appendChild(this.div_);
}
MyOverlay.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
}
MyOverlay.prototype.draw = function() {
var projection = this.getProjection();
var position = projection.fromLatLngToDivPixel(this.getMap().getCenter());
var div = this.div_;
div.style.left = position.x + 'px';
div.style.top = position.y + 'px';
div.style.display = 'block';
};
overlay = new MyOverlay( { map: map } );
//fill x,y coordinates (from lat/lng points)
pixel_coordinates[0] = overlay.getProjection().fromLatLngToContainerPixel(p1);
pixel_coordinates[1] = overlay.getProjection().fromLatLngToContainerPixel(p2);
//calculate hypotenuse
var distance = Math.round(
Math.sqrt(
Math.pow(Math.abs(pixel_coordinates[0].x - pixel_coordinates[1].x),2)
+
Math.pow(Math.abs(pixel_coordinates[0].y - pixel_coordinates[1].y),2)
)
);
console.log(pixel_coordinates[0].x + ', ' + pixel_coordinates[0].y);
console.log(pixel_coordinates[1].x + ', ' + pixel_coordinates[1].y);
console.log(distance);
问题在于 pixel_coordinates 接收的像素坐标与地图中的原始 p1 和 p2 点不匹配。有人能发现错误吗?
更新:它已经工作了,只要确保在计算像素坐标之前使用 map.fitBounds(viewport) :)
【问题讨论】:
-
当时你的问题还有效吗,还是你解决了?如果你修复了它,你应该关闭它,或者发布你自己的答案并标记为正确。
-
对不起,这是我第一次解决问题,距离发布只有几分钟的路程。代码工作,本身没有解决方案,只需按照更新说明进行操作(避免在获取 fromLatLngToContainerPixel 数据后使用 fitBounds。
标签: javascript jquery google-maps-api-3