Adding Markers on Google Maps (with more functionalities)

This tutorial is out of date as of version 3 of Google Maps. Please see this great answer at Stack Overflow for an updated version on how to add markers.

I modified my previous markers example to show off further functionalities:

  • To pop up an info window with marker description.
  • To handle clicks and create new markers.
  • To use markers with custom images.

Extended Google Map Markers

To pop up an info window with marker description
Google maps handles clicks through event listeners. Thus, to open the info window we use the GEvent object:

GEvent.addListener(marker, 'click',
      function() 
      {
         var htmlString = "<font color=\"#6387A5\" size=\"1\" 
                                 face=\"Verdana, Arial, Helvetica, sans-serif\">"+
                          description+"<br/>" + 
                          "(" + latitude + "," + longitude + ")</font>";
         marker.openInfoWindowHtml(htmlString);
      }
   );

The addListener method takes your marker, event type, and a callback function. The callback function is executed when the event is fired, and it calls marker.openInfoWindowHtml which opens an info window.

We also pass a string with the openInfoWindowHtml method, which will be displayed in the info window.

To handle clicks and create new markers
We also handle clicks on the map with GEvent, but this time we add a listener by passing the map instead of the marker:

GEvent.addListener(map, "click", function(overlay, location) {
         
         if( overlay )
         {
            // clicked on something other than the map
            
         }
         else
         {
            var description = prompt("Please enter marker description", "");
            
            // create a new marker
            if( description != null )
               addMarker(location,description);
         }
         
         
      });

I had an issue that triggered the map event when clicking on an info window. Ideally we should be able to tell where the click came from, and handle the event appropriately. This is possible with the callback function taking two arguments: an overlay, and the coordinates of the click.

The first argument is the overlay that was clicked by the user; for example markers and info windows. Therefore, when the first argument is not an overlay we can safely say that the user clicked on the map.

To use markers with custom images

We use the GIcon object to create markers with custom images. Once we create an instance of GIcon we pass it into the GMarker constructor; displaying the custom image instead of the default marker.

In the example we randomly use one of the three custom markers:
Green MarkerBlue MarkerYellow Marker

// create new gicon to use with the marker
var customIcon = new GIcon();
   
// put in random image
var pos = Math.floor(Math.random()*3);
var images = new Array("images/marker_green.png",
"images/marker_blue.png",
"images/marker_yellow.png");
customIcon.image = images[pos];
   
customIcon.iconSize = new GSize(20, 34);
customIcon.iconAnchor = new GPoint(10, 34);
customIcon.infoWindowAnchor = new GPoint(10, 0);
   

// create new marker
var marker = new GMarker(location,customIcon);
About these ads

16 Responses to “Adding Markers on Google Maps (with more functionalities)”


  1. 1 Robert Saturday, 23 August 2008 at 11:23 am

    Very helpful tutorial!

    Is it possible to be done with middle click (left click is used to zoom in the map)…?

  2. 2 IT Outsourcing | Web Development | Globalprompt Wednesday, 15 October 2008 at 1:50 am

    I am using custom icon for google map. But I am not able to add action listener to it.

    http://www.caricarimakan.com/printUrl/2

    can someone help me ?

    Thanks

  3. 3 marcelpad Wednesday, 15 October 2008 at 9:09 am

    To add a listener to a marker you need to use the GEvent.addListener() function.

    More info here http://code.google.com/apis/maps/documentation/reference.html#GEvent.

    Here is a quick example:

    var marker = new GMarker(latlong,customIcon);

    GEvent.addListener(marker, ‘click’,
    function()
    {
    // do something on click
    }
    );

    Hope that helps!

  4. 4 Simón Algorta Tuesday, 28 October 2008 at 8:14 am

    I have embeded my map in a jsp and i have a request response servlet as well. ¿where do i write this code? ¿in the servlet?

  5. 5 Simón Algorta Tuesday, 28 October 2008 at 9:19 am

    ok im sorry that was a silly question…

  6. 6 Pol Friday, 15 May 2009 at 8:36 pm

    Hello Marcel,

    Thanks for your post, thanks to you I succeded to add more markers on a map and more infowindow.

    I made a new version of the Google Latitude Badge.

    You can see it live here: http://zetransporter.blogspot.com/2009/05/google-latitude-badge-improved.html

    Tell me what you think !

    Cya :)

  7. 7 Caleb Tan Wednesday, 27 May 2009 at 8:10 am

    Good job! You are the pride of Malaysia :D.

  8. 8 marcelpad Thursday, 28 May 2009 at 6:15 pm

    Hi Pol. I am happy that the post was helpful to you. I am going to go check out your app.

  9. 10 Jobo Tuesday, 6 October 2009 at 1:53 pm

    Thanks for the post. your codes and scripts are very usefull

  10. 11 Peter Thursday, 15 October 2009 at 12:32 am

    I don’t know how to incorporate those 4 lines you give into the entire script.

    Please put the whole chunk of script from start to end tags so I can get started. I’ve got a map working but your code does not produce a marker on my map.

    Thanks

  11. 12 BISHAL BUDHAPIRTHI Thursday, 17 February 2011 at 7:07 am

    hi marcel pad,
    You are star. Does this code applies for Google maps V3. Your codes are different to V3. If you could post the loop ideas to create marker and info. that would be so awesome.

  12. 13 Shane Monday, 30 May 2011 at 12:21 pm

    Thanks for the info but where do I start. Can you post the whole code?? Thank you so much!! :)

  13. 14 candlestick patterns Wednesday, 8 August 2012 at 6:19 pm

    You are so awesome! I don’t suppose I have read something like that before. So good to find someone with a few original thoughts on this topic. Really.. many thanks for starting this up. This website is something that is needed on the internet, someone with a bit of originality! Check out my website to get more info about forex, if you like.

  14. 15 blogspot.fr Sunday, 5 May 2013 at 10:29 pm

    At that time use of the pills, so hard evidence as to
    their overuse are Chitosan, Chromium, DiCaffeine Malate,
    and Synephrine HCI. While research shows that green coffee diet decreases the risk for carcinoma such as esophageal cancer.
    A new product called the green tea consumption
    in the country is 1. Green coffee diet vitamins provide the
    human body of the package too. Dissolve it and add to
    the cool down phase. Some studies have shown that drinking four cups of green tea a day, I’ll take a Source Naturals to make up for deficiencies.


  1. 1 Louise Ventris » links for 2009-11-13 Trackback on Saturday, 14 November 2009 at 9:03 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s




Hello

My name is Marcel Tjandraatmadja, and I live in Melbourne, Australia. I have a special interest in PHP and web applications.
I also enjoy problem solving with C#, C, and C++.

My interests are also Aikido, roller blading, and music from my favorite bands.

Curriculum Vitae

See my linked in page here.

Contact

Drop me a message at marcel.tjandra@gmail.com.

my del.icio.us

Posts

html hit counter

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: