我在称为p1和p2的地图中有2(lat,lng)标记。我需要计算在像素中从p1到p2的多边形的长度。Google Maps API 3:以像素为单位计算多边形的长度
这是我通过获取斜边值目前的解决方案:
//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(视口)坐标:)
你的问题仍然有效吗?或者你解决了吗?如果你修复了这个问题,你应该关闭它,或者张贴你自己的答案并且标记为正确的。 – nrabinowitz
对不起,这是我第一次解决问题只需几分钟的时间发布。代码工作本身没有解决方案,只需按照更新说明进行操作即可(避免在获取fromLatLngToContainerPixel数据后使用fitBounds。) – andufo