Google maps: Live drawing and updating a Polyline
You need to update the polyline with the new path (the path that has been updated with the new point):
// get existing path
var path = poly.getPath();
// add new point
path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
// update the polyline with the updated path
poly.setPath(path);
code snippet: (click on map to add points to the polyline)
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var poly = new google.maps.Polyline({
map: map,
path: []
})
google.maps.event.addListener(map, 'click', function(evt) {
// get existing path
var path = poly.getPath();
// add new point (use the position from the click event)
path.push(new google.maps.LatLng(evt.latLng.lat(), evt.latLng.lng()));
// update the polyline with the updated path
poly.setPath(path);
})
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
Try the code below:
var path = poly.getPath().getArray();
path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
poly.setPath(path);