gpt4 book ai didi

javascript - 谷歌地图 API 3 : Calculating length of polygon in pixels

转载 作者:行者123 更新时间:2023-11-28 10:08:40 25 4
gpt4 key购买 nike

我在 map 上有 2 个(经纬度)标记:p1 和 p2。我需要计算从 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 接收的像素坐标与 map 中的原始 p1 和 p2 点不匹配。有人能发现错误吗?

更新:它已经可以工作了,只需确保在计算像素坐标之前使用map.fitBounds(viewport):)

最佳答案

上面的代码有效,只是在获取 fromLatLngToContainerPixel 数据后避免使用 fitBounds 。

关于javascript - 谷歌地图 API 3 : Calculating length of polygon in pixels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7810717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com