Search code examples
google-maps-api-3polyline

Drawing polyline similar to drawing of polyline in DrawingManager


This is how I draw my polyline where I click the first point and the polyline is drawn after I click the second point on the map canvas:

Sample google.maps.Polyline

This how polyline is drawn with the DrawingManager:

Sample Drawing Manager

I'd like to draw my regular polyline the same way that is drawn by DrawingManager where the line is continued to show where I move my mouse across the map canvas.

Thanks,


Solution

  • This works for me, one important detail was specifying clickable: false when constructing the polyline, otherwise it didn't register the click event on the map.

    <!DOCTYPE html>
    <html>
      <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <title>Complex Polylines</title>
        <style>
          html, body {
            height: 100%;
            margin: 0;
            padding: 0;
          }
          #map {
            height: 100%;
          }
        </style>
      </head>
      <body>
        <div id="map"></div>
        <script>
    var poly;
    var map;
    var existingPolylinePath;
    var tempPoly;
    
    function initMap() {
      map = new google.maps.Map(document.getElementById('map'), {
        zoom: 7,
        center: {lat: 41.879, lng: -87.624}  // Center the map on Chicago, USA.
      });
    
      poly = new google.maps.Polyline({
        strokeColor: '#000000',
        strokeOpacity: 1.0,
        strokeWeight: 3,
        map: map,
        clickable: false
      });
    
      tempPoly = new google.maps.Polyline({
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 3,
        map: map,
        clickable: false
      });
    
      // Add a listener for the click event
      map.addListener('click', addLatLng);
    
      map.addListener('mousemove', function(event) {
        existingPolylinePath = poly.getPath();
    
        if (existingPolylinePath.length > 0) {
            tempPoly.setPath([existingPolylinePath.getAt(existingPolylinePath.length - 1), event.latLng]);
        }
      });
    }
    
    // Handles click events on a map, and adds a new point to the Polyline.
    function addLatLng(event) {
      var path = poly.getPath();
    
      // Because path is an MVCArray, we can simply append a new coordinate
      // and it will automatically appear.
      path.push(event.latLng);
    
      // Add a new marker at the new plotted point on the polyline.
      var marker = new google.maps.Marker({
        position: event.latLng,
        title: '#' + path.getLength(),
        map: map
      });
    }
        </script>
        <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
      </body>
    </html>