Google Map v3 Markers and Infowindow with jQuery – I

I wanted to create my own custom Google map for my other website, so I’ve been playing with Google Map JavaScript API v3 lately. I wanted to add some basic functionality to the map, where I could add/remove markers, as well as save marker with some information in the database. Since most of us use jQuery in our websites, I have also added jQuery support for some events and Ajax requests.

Add remove Google Marker

Before we start, you need to obtain Google Map API key from Google API console and replace “{GOOGLE-MAP-API-KEY}” with your own API key, I think 25,000 requests/day is free, which is more than enough for small websites.

Have a look at the basic structure of our custom Google Map page below, I’ve declared application as HTML5 using the <!DOCTYPE html> declaration, included Maps API JavaScript and jQuery and a div element with id “google_map” where map will be displayed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key={GOOGLE-MAP-API-KEY}&sensor=false"></script>

<script type="text/javascript">
    $(document).ready(function() {
        //map stuff goes here
    });
</script>

<style type="text/css">
    #google_map {width: 90%; height: 500px;margin-top:0px;margin-left:auto;margin-right:auto;}
    h1.heading{text-align:center;font: 18px Georgia, "Times New Roman", Times, serif;}
</style>

</head>
<body>

    <h1 class="heading">My Google Map</h1>
    <div align="center">Right Click to Drop a New Marker</div>
    <div id="google_map"></div>

</body>
</html>

Loading Google Map

Normally the Google map is loaded like this: <body onload=”initialize()”>, but since we have included jQuery in our document, we can just call the function within the jQuery .ready(), which will automatically be executed after the DOM is ready and there will be no difference in the map functionality.

Before we initialize and load the Map, Google map allows us to set few things (such as level of zoom, scale/ pan / zoom) in Map options object. And just set the Coordinates (longitude and latitude), that’s all you need to include the Google map in our websites.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$(document).ready(function() {
    var mapCenter = new google.maps.LatLng(47.6145, -122.3418); //Google map Coordinates
    var map;
    map_initialize(); // load map
    function map_initialize(){
       
        //Google map option
        var googleMapOptions =
        {
            center: mapCenter, // map center
            zoom: 17, //zoom level, 0 = earth view to higher value
            panControl: true, //enable pan Control
            zoomControl: true, //enable zoom control
            zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL //zoom control size
        },
            scaleControl: true, // enable scale control
            mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
        };
       
        map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);    
    }
});

Dropping a New Marker

Within the map initialize function, I’ve added an event listener, when user rights click on the map, the event gets triggered, and then we can add a new marker using the google.maps.Marker constructor, specifying its properties in marker options.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$(document).ready(function() {
var mapCenter = new google.maps.LatLng(47.6145, -122.3418); //Google map Coordinates
var map;
map_initialize(); // load map
function map_initialize(){
    //Google map option
    var googleMapOptions =
    {
        center: mapCenter, // map center
        zoom: 17, //zoom level, 0 = earth view to higher value
        panControl: true, //enable pan Control
        zoomControl: true, //enable zoom control
        zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL //zoom control size
        },
        scaleControl: true, // enable scale control
        mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
    };
    map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);
   
        //##### drop a new marker on right click ######
    google.maps.event.addListener(map, 'rightclick', function(event) {
        var marker = new google.maps.Marker({
            position: event.latLng, //map Coordinates where user right clicked
            map: map,
            draggable:true, //set marker draggable
            animation: google.maps.Animation.DROP, //bounce animation
            title:"Hello World!",
            icon: "http://localhost/google_map/icons/pin_green.png" //custom pin icon
        });
    });
}
});

Displaying Info Window (InfoWindow)

To display infoWindow, I’ve added another block of Javascript code in the initialize function. The contentString variable holds the HTML content of the infoWindow, it contains a heading and the description. We need to set the content of the infoWindow using infowindow.setContent(). The way to display infoWindow is by adding an event listener. The event listener makes the infoWindow pop-up when user clicks on the marker object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
$(document).ready(function() {
var mapCenter = new google.maps.LatLng(47.6145, -122.3418); //Google map Coordinates
var map;
map_initialize(); // load map
function map_initialize(){
    //Google map option
    var googleMapOptions =
    {
        center: mapCenter, // map center
        zoom: 17, //zoom level, 0 = earth view to higher value
        panControl: true, //enable pan Control
        zoomControl: true, //enable zoom control
        zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL //zoom control size
        },
        scaleControl: true, // enable scale control
        mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
    };
    map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);
   
        //##### drop a new marker on right click ######
    google.maps.event.addListener(map, 'rightclick', function(event) {
        var marker = new google.maps.Marker({
            position: event.latLng, //map Coordinates where user right clicked
            map: map,
            draggable:true, //set marker draggable
            animation: google.maps.Animation.DROP, //bounce animation
            title:"Hello World!",
            icon: "http://PATH-TO-YOUR-WEBSITE-ICON/icons/pin_green.png" //custom pin icon
        });
       
        //Content structure of info Window for the Markers
        var contentString = $('<div class="marker-info-win">'+
        '<div class="marker-inner-win"><span class="info-content">'+
        '<h1 class="marker-heading">New Marker</h1>'+
        'This is a new marker infoWindow'+
        '</span>'+
        '</div></div>');
           
        //Create an infoWindow
        var infowindow = new google.maps.InfoWindow();
       
        //set the content of infoWindow
        infowindow.setContent(contentString[0]);
       
        //add click event listener to marker which will open infoWindow          
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker); // click on marker opens info window
        });
       
    });
}
});

Remove a Marker from the Map

At this point we have successfully loaded the Google map, added a marker and displayed the infoWindow. Now it’s time to remove the added markers from the map. We can simply do that by adding another listener to our delete button, which will be present inside the infoWindow. Notice the contentString variable? I have added a “remove” button at the end, but within the div element. We just need to find this button using .find() method in the DOM Tree, then we add a listener to it, and wait for user to click on the remove button. When user clicks the remove button, we simply trigger the marker.setMap(null) to remove that particular marker from the map.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
$(document).ready(function() {
var mapCenter = new google.maps.LatLng(47.6145, -122.3418); //Google map Coordinates
var map;
map_initialize(); // load map
function map_initialize(){
    //Google map option
    var googleMapOptions =
    {
        center: mapCenter, // map center
        zoom: 17, //zoom level, 0 = earth view to higher value
        panControl: true, //enable pan Control
        zoomControl: true, //enable zoom control
        zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL //zoom control size
        },
        scaleControl: true, // enable scale control
        mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
    };
    map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);
   
    //##### drop a new marker on right click ######
    google.maps.event.addListener(map, 'rightclick', function(event) {     
        var marker = new google.maps.Marker({
            position: event.latLng, //map Coordinates where user right clicked
            map: map,
            draggable:true, //set marker draggable
            animation: google.maps.Animation.DROP, //bounce animation
            title:"Hello World!",
            icon: "http://PATH-TO-YOUR-WEBSITE-ICON/icons/pin_green.png" //custom pin icon
        });
       
        //Content structure of info Window for the Markers
        var contentString = $('<div class="marker-info-win">'+
        '<div class="marker-inner-win"><span class="info-content">'+
        '<h1 class="marker-heading">New Marker</h1>'+
        'This is a new marker infoWindow'+
        '</span>'+
        '<br /><button name="remove-marker" class="remove-marker" title="Remove Marker">Remove Marker</button></div></div>');
           
        //Create an infoWindow
        var infowindow = new google.maps.InfoWindow();
       
        //set the content of infoWindow
        infowindow.setContent(contentString[0]);
       
        //add click listner to marker which will open infoWindow         
        google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker); // click on marker opens info window
        });
       

        //###### remove marker #########/
        var removeBtn   = contentString.find('button.remove-marker')[0];
        google.maps.event.addDomListener(removeBtn, "click", function(event) {
            marker.setMap(null);
        });
    });
}
});

Conclusion

So far, we are able to load a Google map on a HTML page and display the marker information on info Windows. Now it’s time for us to move to next step, which includes loading markers from XML, editing and saving marker information to the database. You can see the demo and also download the sample file below. Good Luck!
Next : Loading Google Map Markers from XML and Editing & Saving Information in Database.

Download Demo

19 Comments Add Comment

  • do you have a latest version ? cause I think some of the codes are deprecated alredy

     Reply
  • I am the event manager of a amateur radio event. I have been trying to create a Locarion Map where each user can mark their location on the map and have that marker save so others can see who is operating where.

    I haven’t tried your code yet, but I need to create something like this but where a user can input his “callsign” ie WD8MBE and their “category” ie 1H and their coordinates.
    Allow the user to position marker at their operating location and drop the marker.
    I also need to be able to save the marker locations.

    I have been able to create a map with multiple markers with info window showing the above. However, if the page is refreshed or they go to another web page then come back to the map, the placed markers are gone, not saved.

    Any suggestions or help would be greatly appreciated.

     Reply
  • Hello, I downloaded the zip file and edited the code, in that, I replaced the YOUR API KEY with my API key and also, I changed the green pin location from the https://….to my PCs location “C:\Users\……..\icons\pin_blue.png”. When I run the file in a browser, no google map comes in the background, only the heading and subheading is coming with entire area as white instead of the Google map.
    Thanks much.

     Reply
  • Good day all,

    I would like to ask if anyone has had a problem with the content string as I cant seem to get the save or remove buttons to show.

    Any help would be greatly appriciated.

     Reply
  • i user removebtnSecton on my app but give me an error

    TypeError: contentString.find is not a function

     Reply
  • Outstanding, even now in 2016 this is still a fully working and perfectly explained tutorial for Google Maps.
    Thanks for that!

     Reply
  • Renan Marchetto

    I need to change the markers colors by showing a picklist onclick. For example: A red Marker, with the inner info ‘Red’, when clicked shows a picklist with others colors (blue, black,… ), when selected the color is changed and the inner info is changed too.
    There are any: google.maps function to facilitate that, I would like an example if possible.
    I couldn’t find anything like that on internet. I can only find how to put a marker and edit that, but not how to do something more elaborate like this, I don’t even know if it is possible using google api.

     Reply
  • hellow, i would like to keep fetching existing markers from mysql database and when mouse right click show only one green marker, just allow the user to add only one marker a time.(sorry for my bad english)

     Reply
  • The limitation of 25k access/day doesn’t exist anymore WHEN accessing it by PC/Notebook since you dont have to enter a license key. But when implementing google maps v3 into an app you have to enter a key and the limit is still active there.

     Reply
  • Hi ! Do you know why I can’t add a marker/infobox in a seperate function? I want to show the instagram pictures to the given coordinates but It gives a redirect to (e.g) http://www.yepcheck.com/instaroundme/50.110922,8.682127 and the problem lies in this piece of code.

    var markerib = new google.maps.Marker({
    map: map
    ,position: markerPositionx
    ,visible: true
    });

     Reply
  • Thanks a lot, buddy! google maps rocks!

     Reply
  • hello great post i love it … only one question .. how as you can limit the map to display for example only one state or just certain area of the map.

     Reply
  • Hello !
    Thank you very much for this article !
    To go further, i would like to add an image to a new marker. Do you have some advices for me ?

    Thank you !!!

     Reply
  • Congrats for the nice article, the sample is very understandable and customizable.
    Thank you for this!

     Reply
  • Hello Saran,
    Thank you so much for such wonderful article. It straight and clear to understand. It saved lot of my time.
    :-)

     Reply
  • hello this is very interesting your code. I would like to know how to add an item while clicking a button and not a right click
    thank you

     Reply
    • Its very simple.

      Just Change rightclick event to click. I have change it just to have only one marker.
      I have added code portion where you can compare changes. Rest is same.

      Thank you

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      var marker = null;
          google.maps.event.addListener(map, 'click', function(event) {
             
              if(marker){
                  marker.setMap(null);
              }
             
              marker = new google.maps.Marker({
                  position: event.latLng, //map Coordinates where user right clicked
                  map: map,
                  draggable:true, //set marker draggable
                  animation: google.maps.Animation.DROP, //bounce animation
                  title:"Hello World!",
                  icon: "icons/pin_blue.png" //custom pin icon
              });