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

The Google Maps API V3 gives you control over how to input data and create custom Google maps. If you have a list or array of latitude and longitude coordinates you can specify that Google uses the array to create a route or polyline on a map. For example, you could create a line following the mountain contours on a hiking trail or a shipping route that weaves around a series of islands.

Instructions

    • 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.

Related Searches:

References

Comments

Related Ads

Featured