Search code examples
javascriptjqueryjquery-pluginsjquery-gmap

How to draw polyline using gMap and jQuery?


I would like to use gMap jQuery plugin in my project. I succesfully display Google map, I can display some markers, but I cannot find any way how to draw polyline.

I have this JS code:

$(window).ready(function () {
  var data = {
    'latitude': 0.000000,
    'longitude': -180.000000,
    'zoom': 3,
    'maptype': "terrain",
  };
  var gps_coordinates = {
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 2,
    path: [
      {'latitude':37.772323,'longitude':-122.214897},
      {'latitude':21.291982,'longitude':-157.821856},
      {'latitude':-18.142599,'longitude':178.431000},
      {'latitude':-27.467580,'longitude':153.027892}
    ]
  };

  $('#map').gMap(data);
  $('#map').gMap("Polyline", gps_coordinates);
});

In gMap documentation is this note:

You can also use some of internal gmap functions.

So I suppose, I can use google.maps.Polyline function to draw a polyline. But how?


Solution

  • I'm not familiar with the gMap plugin. However if I was doing this just using Google Maps API 3, I'd do something like this:

    var homeLatlng= new google.maps.LatLng(0, -180);
    
    var myOptions = {
        zoom: 3,
        center: homeLatlng,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    var pathLatLng;
    
    var paths = [
          {'latitude':37.772323,'longitude':-122.214897},
          {'latitude':21.291982,'longitude':-157.821856},
          {'latitude':-18.142599,'longitude':178.431000},
          {'latitude':-27.467580,'longitude':153.027892}
        ];
    
    for (var i = 0; i < paths.length; i++) {
        pathLatLng = new google.maps.LatLng(paths[i].latitude, paths[i].longitude);
    
        path = new google.maps.Polyline({
            path: [homeLatlng, pathLatLng],
            strokeColor: "##FF0000",
            strokeOpacity: 1.0,
            strokeWeight: 2,
            geodesic: true,
            map: map
        });
    }
    

    this map draws curved lines indicating the true shortest route between two destinations. If you just want straight lines, set the geodesic attribute to false