• Create a google Map with Custom Markers

    Posted on May 28, 2012 by in Javascript, Other Programming

    If you have never used google maps API before, I suggest you go through the article Create a basic map using Google Maps API to get acquainted with creating maps. In this article we create custom markers and attach custom message to the markers.

    Click on the link below to view the demo.


    Custom Markers

    In real time applications more often than not a situation would arise where you would like to have different icon or icons instead of default icons provided by google, For example there might be situation where you want to have a green marker/ red marker according to status of work at the location, or you might want a different icon for a location type or you might simply want a different icon instead of default icon. Icon can easily changed by using the code below

     
    
       var image = 'images/youricon.png'; 
    
       var marker = new google.maps.Marker({
           position: location,
           map: map,
           icon: image
       });
    

    The code above changes the default icon with youricon.png. If you want different markers for your maps as the one’s used in the demo, you might want to try download it here. You will find huge collection of icons in different categories and you can also generate icons in the color you like. Please go through the license before using them in you project.

    Attaching a message to message to the marker

    google.maps.InfoWindow can be used to show a popup with important information for the users on clicking the marker. We assign a msg to each marker and call it on the click event as given in the code below.

       var marker = new google.maps.Marker({
                    position: location,
                    map: map,
    		icon: image
                });
    			
       var title = 'Location : ' + MarkerData[i].Name;
       marker.setTitle(title);
    			
       //attach message 
       var msg = 'Location : ' + MarkerData[i].Name + '<br/> ';
           msg = msg + 'Location Type : ' + MarkerData[i].LocationType + '<br/> ';
                
       var infowindow = new google.maps.InfoWindow({
            content: msg,
    	size: new google.maps.Size(120, 150)
    	});
       google.maps.event.addListener(marker, 'click', function () {
         infowindow.open(map, marker);
       });
    
    

    Now let us put it all together, The code below uses data from JSON object , you can get the data into the JSON object $.ajax if required. The code shows different markers according to location type.

     
    <!DOCTYPE html>
    <html>
      <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <style type="text/css">
          html { height: 100% }
          body { height: 100%; margin: 0; padding: 0 }
          #map_canvas { height: 100% }
        </style>
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&key=AIzaSyD0X4v7eqMFcWCR-VZAJwEMfb47id9IZao">
        </script>
        <script type="text/javascript">
    	  var map;
    	  var MarkerData = [{"Name":"Penn Station","Latitude":40.75058,"Longitude":-73.99358,"LocationType":"Station"},
    	  		    {"Name":"Empire State Building","Latitude":40.748039,"Longitude":-73.985753,"LocationType":"Attraction"},
    			    {"Name":"Times Square","Latitude":40.756631,"Longitude":-73.988369,"LocationType":"Attraction"},
    			    {"Name":"Central Park","Latitude":40.770641,"Longitude":-73.974196,"LocationType":"Attraction"},
    			    {"Name":"Crowne Plaza Times Square","Latitude":40.760342,"Longitude":-73.98482,"LocationType":"Hotel"},
    		  	    {"Name":"Sheraton New York Hotel ","Latitude":40.739714,"Longitude":-73.989315,"LocationType":"Hotel"}]
    					  
          function initialize() {
            var myOptions = {
              center: new google.maps.LatLng(40.756631,-73.988369),
              zoom: 14,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            	map = new google.maps.Map(document.getElementById("map_canvas"),
                myOptions);
    	
    		
    		for (i=0;i<MarkerData.length;i++){
    			var image;
    			if (MarkerData[i].LocationType == "Station") {
                	image = 'images/train.png'; 
    			} else if (MarkerData[i].LocationType == "Hotel") {
    				image = 'images/lodging.png'; 
    			}
    			else if (MarkerData[i].LocationType == "Attraction") {
    				image = 'images/monument.png'; 
    			}		
    		
    			var location = new google.maps.LatLng(MarkerData[i].Latitude,MarkerData[i].Longitude);
                var marker = new google.maps.Marker({
                    position: location,
                    map: map,
    				icon: image
                });
    			
    			var title = 'Location : ' + MarkerData[i].Name;
                marker.setTitle(title);
    			
    			//attach message 
                var msg = 'Location : ' + MarkerData[i].Name + '<br/> ';
    			msg = msg + 'Location Type : ' + MarkerData[i].LocationType + '<br/> ';
                attachMessage(marker, msg);
    		 }
          }
    	  
    	function attachMessage(marker, msg) {
    		var infowindow = new google.maps.InfoWindow({
    			content: msg,
    			size: new google.maps.Size(120, 150)
    		});
    		google.maps.event.addListener(marker, 'click', function () {
    			infowindow.open(map, marker);
    		});
    	}
        </script>
      </head>
      <body onLoad="initialize()">
        <div id="map_canvas" style="width:100%; height:100%"></div>
      </body>
    </html>
    

    To see the working demo of the above code click on the link below.

    For downloading complete set google maps api examples, click the link below

    NOTE : If you download the source from the example, please do change the API KEY. If you do use the icons, please go to http://mapicons.nicolasmollet.com/ and read and license and give credit where ever neccessary.

    Be Sociable, Share!
      Post Tagged with ,

    2 Responsesso far.

    1. Kazi says:

      I am looking for make a Google map displaying multiple address for about couple of days. This is the best tutorial I have ever came across.
      But is there any way instead of using altitude and latitude, use actual address?
      Thanks a lot for an awesome tutorial.

    Leave a Reply