How can I add point on polyline beetwen two existing points on click polyline event? Thank you!
views:
244answers:
1If you are just talking about a Polyline
with only 2 points, you could use the center of a LatLngBounds
containing the Polyline
. Google maps api v3 doesn't implement the Polyline.getBounds()
function, though. So you can extend the Polyline
class to include a getBounds
function:
google.maps.Polyline.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds();
this.getPath().forEach(function(e) {
bounds.extend(e);
});
return bounds;
};
Polyline.getBounds()
on a line with only 2 points will contain the area to include this line. The center of this bounds should be the exact center of your line. If the Polyline
includes more than 2 points, the center will not fall on the center of the line clicked, but the center of the bounds that includes all points. If you want to use mutli-segment Polylines with this function, it will take more math to calculate which segment was clicked.
Here is a small example using a 2 point 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>