Friday, July 13, 2012

Google Maps - Display points with different markers

If you want to display different points with different markers this is for you.  Say you want to display points with two markers, let's first create markers:

Let's get started:

function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(28.2,-89.6), 6);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
   
        // Create our "tiny" marker icon
        var greenIcon= new GIcon(G_DEFAULT_ICON);
        greenIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/icons/green-dot.png";
        greenmarker = { icon:greenIcon };

        var redIcon= new GIcon(G_DEFAULT_ICON);
        redIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/icons/red-dot.png";
        redmarker = { icon:redIcon };

        var greenIcon= new GIcon(G_DEFAULT_ICON);
        greenIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/icons/green-dot.png";
        greenmarker = { icon:greenIcon };

        var redIcon= new GIcon(G_DEFAULT_ICON);
        redIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/icons/red-dot.png";
        redmarker = { icon:redIcon };


Now let's create a set of data points:

var locations = [['42001', 26.0, - 90.0,    1],
['42002',26.0, -94.0, 2],
['42007',30.1, -88.9, 3],
['42019',27.9, -95.0, 4],
['42020',27.0, -96.5, 5],
['42035',29.2, -94.4, 6],
['42036',28.5, -84.5, 7],
['42038',27.4, -92.6, 8],
['42039',28.8, -86.0, 9],
['42040',29.2, -88.3, 10],  ];

Now, let's create marker with the data point and marker options:

function createMarker(point, moption, id) {
      var marker = new GMarker(point, moption);


      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindow("Point " + id + "");
      });
      return marker;
 }

Putting all together:

// Using first marker
for (i = 0; i < locations.length; i++) {
  var latlng = new GLatLng(locations[i][1], locations[i][2]);
   map.addOverlay(createMarker(latlng, greenmarker, locations[i][0]));
}

//Using second marker 
map.addOverlay(createMarker(new GLatLng(29.3, -90.0), redmarker, 'GDIL1'));
  }
 }

No comments: