如何在点击折线事件的两个现有点之间添加折线上的点?
谢谢!
最佳答案
如果您仅在讨论仅包含2点的Polyline
,则可以使用包含LatLngBounds
的Polyline
的中心。不过,Google Maps api v3没有实现Polyline.getBounds()
函数。因此,您可以扩展Polyline
类以包含getBounds
函数:
google.maps.Polyline.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds();
this.getPath().forEach(function(e) {
bounds.extend(e);
});
return bounds;
};
仅2点的直线上的
Polyline.getBounds()
将包含要包括该直线的区域。此边界的中心应该是直线的确切中心。如果Polyline
包含2个以上的点,则中心不会落在所单击线的中心上,而是落在包含所有点的边界的中心上。如果要通过此功能使用多段折线,则需要花费更多的数学才能计算出单击了哪个段。这是一个使用2点
Polyline
的小示例:<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Right in Two</title>
<style type="text/css">
#map-canvas {
height: 500px;
}
</style>
<script type="text/javascript"
src="http://www.google.com/jsapi?autoload={'modules':[{name:'maps',version:3,other_params:'sensor=false'}]}"></script>
<script type="text/javascript">
function init() {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(37.790234970864, -122.39031314844),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var points = [
new google.maps.LatLng(40.785533,-124.16748),
new google.maps.LatLng(32.700413,-115.469971)
];
var line = new google.maps.Polyline({
map: map,
path: points,
strokeColor: "#FF0000",
strokeWeight: 2,
strokeOpacity: 1.0
});
google.maps.Polyline.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds();
this.getPath().forEach(function(e) {
bounds.extend(e);
});
return bounds;
};
google.maps.event.addListener(line, 'click', function(e){
var marker = new google.maps.Marker({
map: map,
position: line.getBounds().getCenter()
});
});
};
google.maps.event.addDomListener(window, 'load', init);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>