How to Draw a Polyline Having an Array of String Locations in Google Maps V3

104 26
    • 1). Open your HTML file and scroll to the section where you define your Google Map.

    • 2). Under the code where you initialize the map define the characteristics of the polyline. For example, type:

      var polylineOptions = {
          strokeColor: '#000000',
          strokeWeight: 3

      In this example, the line's color is set to the hexadecimal color black and the weight of the line is three.

    • 3). Initialize the polyline. For example, type:

      polylineExample = new google.maps.Polyline(polylineOptions);
        polylineExample.setMap(map);

      In this example, we are adding the polyline to the map with the characteristics defined in the "polylineOptions" variable.

    • 4). Create the array of locations by clicking on points on the map. For example, type:

      google.maps.event.addListener(map, 'click', addLatLng);
      }

      In this example, Google listens for the user to click on the map and stores that value in "addLatLng."

    • 5). Create the polyline using the addlatLng function. For example, type:

      function addlatLng (event) {
      var route = polyline.getpath ( );
      route.push (event.latLng);


      Continuing an example, "getpath" returns the array of values assigned to the variable "route" and pushes the new geographical coordinates into the array.

    • 6). Add a location marker for each geographical point along the polyline. For example, type:

      var locMarker = new google.maps.locMarker({
          position: event.latLng,
          title: '#' + route.getLength(),
          map: map
        });
      }

      In this example, Google maps plots the locations on the route or polyline using the data in the "route" array.

    • 7). Save your code and test it. Google Maps displays a line on your map. For each location Google Maps places a marker. The polyline will look similar to a connect-the-dots image on the map.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.