Web International Awards

payday loan

9

SEP 2010 34

Build a POI map using jQuery & Google Maps v3 (revised)

Tutorial preview

In the first revision of this tutorial, you've asked a couple of times if it is possible to display multple POIs at the same time on the map. The answer is yes, you can!

clearOverlays() gone

The clearOverlays() function was used to actually erase all markers on the map (all POIs on the map) when you clicked any link in the sidebar. In order to display multiple POIs on the map, this function must not be used. Therefor, in the revised version of the POI map the function was discarded as well as its unique call in the handle_clicks() function.

addMarker() updated

The original version of the function didn't check before appending a marker to the markersArray if there's already a marker with the same coordinates. That wasn't necessary because such a case wasn't possible because the clearOverlays() function assured there are no markers in the array when the addMarker() function was called. However, discarding the clearOverlays() function results in duplicated markers in the array each time someone clicks multiple times on the same link in the sidebar. To prevent that, we must check before adding a new marker to the array if it doesn't already exist. We do that within the addMarker() function:

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
function addMarker(m_position,m_title,m_infowindow) {
	var mark;
 
	if (markersArray.length!=0) 
	{
		duplicate = false;
		var markcopy;
		var markersCopy = [];
		while(markcopy=markersArray.pop())
		{
			if((markcopy.position.lat()==m_position.lat())&&(markcopy.position.lng()==m_position.lng())) duplicate = true;
			markersCopy.push(markcopy);
		}
		markersArray = markersCopy;
		if(duplicate==false)
		{
			marker = new google.maps.Marker({
			  	position: m_position,
			  	map: map,
				title: m_title
			});
			markersArray.push(marker);
			mark = markersArray.pop();
			google.maps.event.addListener(mark, 'click', function() {
				infoWindow.open(map,mark);
				var stringContent = m_infowindow;
				infoWindow.setContent("<div id=\"infowin-overlay\""+stringContent+"</div>");
 
				overlayHeight = $('#infowin-overlay').height();
				overlayWidth = $('#infowin-overlay').width();
				$('#infowin-overlay').parent().css('height',overlayHeight);
				$('#infowin-overlay').parent().css('width',overlayWidth);
			});
			markersArray.push(mark);
		}
	}
	else
	{
		marker = new google.maps.Marker({
		  	position: m_position,
		  	map: map,
			title: m_title
		});
		markersArray.push(marker);
		mark = markersArray.pop();
		google.maps.event.addListener(mark, 'click', function() {
			infoWindow.open(map,mark);
			var stringContent = m_infowindow;
			infoWindow.setContent("<div id=\"infowin-overlay\""+stringContent+"</div>");
 
			overlayHeight = $('#infowin-overlay').height();
			overlayWidth = $('#infowin-overlay').width();
			$('#infowin-overlay').parent().css('height',overlayHeight);
			$('#infowin-overlay').parent().css('width',overlayWidth);
		});
		markersArray.push(mark);
	}
}

In the above script we do the following: we first check if there's any markers in the array (line 4), and if the array is empty, we create a new marker, add it to the array and add a listener to it (lines 39 to 56). The listener is required because we need a trigger that will display the overlay window when a marker is clicked.

If the array is not empty, we check if the current marker to be added is already in the array. That's done with the while loop between lines 9 and 13. As you can see, the duplicate variable is initialized to false. If there's a marker in the array with the same coordinates as the marker we're trying to add, the value is changed to true. If duplicate variable remains false after the while loop is completed, we can safely add the marker to the array as described in the previous paragraph.

Because the required changes were minor, I decided not to update the entire tutorial, but to simply release the new source codes and show you the new function that does the trick. Therefor, you can view a new demo of the POI map script over here and download the full source code over here.

If you enjoyed this article you can stay updated to new content via our RSS feed or by email.

Published on Thursday, September 9th, 2010 at 8:54 am in jQuery.

About Bogdan Pop

Bogdan Pop is a young Romanian entrepreneur who runs WebRaptor. He is a web developer with awesome design skills, who enjoys writing about everyday's work and usability. He relaxes by taking photos every once in a while and by mixing french electronic music. Connect with him via Twitter.
 
  1. Marcel says: December 12th, 2010 at 8:33 pm

    Hi Bogdan, you’ve helped me a lot, but I still have some questions.
    1.Is it possible to display all markers at the begining?
    2.When I load the page, it centers to place I set, with some zoom. Is it possible to change that zoom when I click on some marker? (I need to zoom in). And is it possible to do it smoothly? Or at least move from one marker to another smoothly, not just jump.
    3.How to display flash content in that bubble when marker is clicked?

    I dont want to waste your time, I will search for the answers on my own, but if you’ll have a little time.. Thank you!

  2. Bogdan Pop says: December 13th, 2010 at 3:59 pm

    Hi Marcel,

    1.Is it possible to display all markers at the begining?

    Yes it is possible. This is the revised version of the tutorial. What you must do on page load is call addMarker(m_position,m_title,m_infowindow) function and add as many marker you need.

    These addMarker calls must be inside the $(document).ready(function() brackets after you init your map.

    Please see original tutorial for the source code explanation on that section. The tutorial’s over < ahref="http://www.webia.info/articles/jquery-articles/build-a-poi-map-using-jquery-google-maps-v3/">here.


    2.When I load the page, it centers to place I set, with some zoom. Is it possible to change that zoom when I click on some marker? (I need to zoom in). And is it possible to do it smoothly? Or at least move from one marker to another smoothly, not just jump.

    Map zoom is originally set by using the zoom property upon map initialization. For zooming when clicking on markers, there’s a piece of code in the handle_clicks() function. Again back to original for source code info.

    Inside handle_clicks() you have map.setCenter(update2Location);. Change this to map.setCenter(update2Location,myzoom); where zoom is a variable with the myzoom you like

    3.How to display flash content in that bubble when marker is clicked?

    each addMarker call sends a m_infowindow variable. This can contain striped content, which include flash objects. just replace all < with < and so on.

    Cheers!
    Hope I’m not too late.

  3. Marcel says: December 14th, 2010 at 10:21 pm

    You’re fast as light. I’ll try it and then reply. Thank you again..

  4. Marcel says: January 12th, 2011 at 3:26 am

    Hi Bogdan, as obviously you helped me a lot. I just finished read a book about google maps api 3 and made some maps, but I have still at least one question. Can you check link removed and tell me what to change to display lightbox image below the map after click on a marker? I know, I have to read some javascript books too, but time is running and I need to move on. Thank you so much.

  5. Bogdan Pop says: January 13th, 2011 at 11:33 am

    Hi Marcel, based on how you design your markers, you have to add click events to them just as you’ve done with the image thumbnails below the map.

    Check http://bit.ly/gqwr69

    Basically, you need
    google.maps.event.addListener(map, ‘click’, function(event) {
    placeMarker(event.latLng);
    });
    }
    and replace placeMarker with you own code that triggers the lightbox.

    Cheers!

  6. Ivan says: January 27th, 2011 at 8:10 pm

    Hi Bogdan,

    Thanks for this extremely practical example.

    I was wondering whether it is possible to:

    1) Open the marker immediately upon clicking a link in the “Our office locations” box

    2) Use a custom icon for each marker


    Cheers,
    Ivan

  7. Bogdan Pop says: January 31st, 2011 at 5:40 pm

    Hi Ivan,
    Markers currently show up only when you click on a certain office location. Additional information is also displayed only after one clicks the marker.

    As for custom icons, you only have to append icon: URL_to_your_icon into the google.maps.Marker object.

  8. Vincent says: March 16th, 2011 at 9:00 pm

    Hello,
    Thank you for this great tutorial. I have a question, is it possible that when the click on the marker, it loads the content in a DIV and not in the tooltip, just as in the example below, but unfortunately that is based on API V2: Google marker click event. Thank you in advance.

  9. Bogdan Pop says: March 17th, 2011 at 8:57 am

    Hello Vincent,

    This is similar to Marcel’s problem. Upon adding a marker, you must add an event listener for it, in the form of:

    google.maps.event.addListener(map, ‘click’, function(event) {
    // do click event here
    });
    }

    This will catch clicks on your markers and run whatever code you put into do click event. Therefor, if you have a div with id marker-content-extra , you could do this with jQuery:

    google.maps.event.addListener(map, ‘click’, function(event) {
    $(‘#marker-content-extra’).html(“A lot of custom HTML in here”);
    });
    }

    You could add html including images, text, sliders, videos etc.

    Bogdan

  10. Vincent says: March 17th, 2011 at 12:57 pm

    Hi Bogdan,

    Thank you for your answer, I’ll try it and I’ll post a demo when I get what I want (sorry for my English, I’m french)

    Vincent

  11. Bogdan Pop says: March 17th, 2011 at 10:41 pm

    You’re welcome Vincent!

  12. Vincent says: March 19th, 2011 at 12:29 pm

    Hi Bogdan,

    Thank you very much for your help I managed to do what I wanted.
    The original idea was to be able to click on the marker and display content in a div, and this, using google maps API V3.
    Based on the following tutorial: http://code.google.com/intl/fr/apis/maps/articles/phpsqlajax_v3.html, here is my code for displaying content on the one hand in the tooltip and other html content in a div:







    Test




    function createXmlHttpRequest() {
    try {
    if (typeof ActiveXObject != ‘undefined’) {
    return new ActiveXObject(‘Microsoft.XMLHTTP’);
    } else if (window[“XMLHttpRequest”]) {
    return new XMLHttpRequest();
    }
    } catch (e) {
    changeStatus(e);
    }
    return null;
    };

    function downloadUrl(url, callback) {
    var status = -1;
    var request = createXmlHttpRequest();
    if (!request) {
    return false;
    }

    request.onreadystatechange = function() {
    if (request.readyState == 4) {
    try {
    status = request.status;
    } catch (e) {
    }
    if (status == 200) {
    callback(request.responseText, request.status);
    request.onreadystatechange = function() {};
    }
    }
    }
    request.open(‘GET’, url, true);
    try {
    request.send(null);
    } catch (e) {
    changeStatus(e);
    }
    };

    function xmlParse(str) {
    if (typeof ActiveXObject != ‘undefined’ && typeof GetObject != ‘undefined’) {
    var doc = new ActiveXObject(‘Microsoft.XMLDOM’);
    doc.loadXML(str);
    return doc;
    }

    if (typeof DOMParser != ‘undefined’) {
    return (new DOMParser()).parseFromString(str, ‘text/xml’);
    }

    return createElement(‘div’, null);
    }

    var map;

    function initialize() {
    var latlng = new google.maps.LatLng(46.7, 2.5);
    var myOptions = {
    zoom: 5,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById(‘map_canvas’), myOptions);

    downloadUrl(“getPoi.php”, function(data) {

    var xml = xmlParse(data);
    var markers = xml.documentElement.getElementsByTagName(“marker”);

    for (var i = 0; i < markers.length; i++) {
    createMarker(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")), markers[i].getAttribute('titre'), markers[i].getAttribute('description'));
    }
    });

    }

    function createMarker(lat, lng, titre, description){
    var latlng = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: titre
    });

    var infobulle = new google.maps.InfoWindow({
    content: titre
    });

    google.maps.event.addListener(marker, 'click', function(event) {
    $('#content_map').html();
    infobulle.open(map, marker);
    });

    }






    contenu left



    Détails



  13. Vincent says: March 19th, 2011 at 12:35 pm

    Sorry for my code, he is too long. So, you can see it in this forum (the last post): http://www.siteduzero.com/forum-83-625251-p1-google-maps-v3.html#r6033610

    Vincent

  14. Mike B says: October 4th, 2011 at 11:39 pm

    In regards to having the markers showing up automatically on the map (without clicking locations in the side-bar), you responded with:

    1.Is it possible to display all markers at the begining?

    “Yes it is possible. This is the revised version of the tutorial. What you must do on page load is call addMarker(m_position,m_title,m_infowindow) function and add as many marker you need.

    These addMarker calls must be inside the $(document).ready(function() brackets after you init your map.

    Please see original tutorial for the source code explanation on that section. The tutorial’s over here.”

    Could you please provide me with an example? I’m a newbie and quite confused as to what you mean.

    Much Appreciated.
    Mike

  15. Bogdan Pop says: October 11th, 2011 at 12:16 pm

    Hi Mike, sorry for the delay.

    In the original article you have the standard calls for the map behavior in the js file.

    At the end of it, you will find the following:

    $(document).ready(function(){
    if($(‘#map’).get(0))
    { // only initialize the map if map is located inside the page
    map = InitMap(null,’map’, centerCoord, true); // initialize the map on default location
    handle_clicks(); // click events handling by jQuery
    }
    });

    After the first closing bracket (the one from the if statement) add any new markers as you want.

    addMarker(GooglePositionObject,title_text,infowindow_content);

    It should look like:
    $(document).ready(function(){
    if($(‘#map’).get(0))
    { // only initialize the map if map is located inside the page
    map = InitMap(null,’map’, centerCoord, true); // initialize the map on default location
    handle_clicks(); // click events handling by jQuery
    }
    addMarker(GooglePositionObject,title_text,infowindow_content);
    });

  16. Mike B says: October 11th, 2011 at 8:32 pm

    Thanks Bogdan! This is what I was looking for. HOWEVER, as a newbie, I’m not sure how to format the “addmarker”…

    What do I replace the bracketed cxontent with? I.e (GooglePositionObject,title_text,infowindow_content);

    I’m quite confused by this. Could you give me an example based on one of the locations you used in your example? I tried replacing “GooglePositionObject with the latitude coordinates, but that didn’t work.

    Any help would be greatly appreciated!

  17. Bogdan Pop says: October 12th, 2011 at 10:44 am

    Hi Mike,

    title_text and infowindow_content are html or raw text strings. The title will be the title of the marker (shown when you hover it on the map) while the infowindow contents is the info displayed in the white bubble that appears when you click the marker.

    The GooglePositionObject is actually a LatLng class in Google maps API, sorry for the confusion (http://code.google.com/apis/maps/documentation/javascript/reference.html#LatLng)

    Here’s the marker reference page http://code.google.com/apis/maps/documentation/javascript/reference.html#Marker

  18. Mike B says: October 12th, 2011 at 5:15 pm

    Hi Bogdan,

    Thanks for taking the time to try and help me figure this out. The links you provided are even more confusing for me – and any other that are likely reading this tutorial (as we’re just learning).

    I under the last two elements with the “addMarker()”, but I have NO idea what the links mean and how to set up the coordinates.

    Would you mind doing an example with one of the locations used in this tutorial? Nothing seems to work when I try?

    Sorry for the annoyance. But once I/we see an example, I’m sure we’ll be like, “Aghh, I know see!”. :)

    I’m being forced/asked for this feature and the project i”m doing is delayed so any help would be greatly appreciated.

    Cheers,
    Mike

  19. Bogdan Pop says: October 12th, 2011 at 10:23 pm

    Try addMarker( new google.maps.LatLng( 23.952162,-13.867187 ), ‘title here’, ‘<p>some content here</p>’);

  20. Mike B says: October 13th, 2011 at 5:36 pm

    Hi Bogdan,

    Thank you once again. That certainly solved the confusion. However, it didn’t work.

    Here’s the application I’m building:
    http://t-zonevibration.com/expandable_store_locator/

    In short, I want ALL the locations in the side-bar to automatically show up on the map – red markers – once the application loads.

    I added the snippet of code you provided above, and set up the coordinates for the first store location (Danforth), however no red markers automatically appear and if you click the Danforth store in the side-bar, the red marker won’t even show up on the map now.

    Could you kindly look at the code when you get a free minute and see where the issue is?

    Thanks in advance,
    M

  21. Bogdan Pop says: October 14th, 2011 at 10:20 am

    On click events work fine (http://twitpic.com/701i6y) .

    Danforth won’t show up on the map because the script tracks all added markers against duplicates (previously declared markers). For some reasons, the marker is added on page load but is not displayed on the map, and that’s why when you click on it it won’t show up as the rest because it is currently considered to be visible.

    I think the problem is you initialize the map on the toggle event, every time. Try initializing the map once and then just toggle the height of the element that wraps it, instead of reinitializing the map.

  22. chungwufei says: January 15th, 2012 at 5:54 pm

    hello bogdan… i want to ask for your help. is it possible like the example here?

    http://gmaps-samples.googlecode.com/svn/trunk/geocoder/singlegeocode.html

    i want to know the long and lat as i click on the marker.

  23. chungwufei says: January 15th, 2012 at 5:55 pm

    anyway… thanks in advance… God Bless…

  24. Bogdan Pop says: February 2nd, 2012 at 10:09 pm

    Really sorry about the delay Chungwufei.

    Do you mean add POIs based on search?

    Yes it is possible, you may as well copy / paste the code from Google and then work with it.

    If you’re asking if the POI map on Webia has a geolocation search feature, no it doesn’t have.

  25. Michael says: May 22nd, 2012 at 3:33 am

    Hi Bogdan!

    I’ve just started fooling around with Google Maps and have been to many sites that seem to cover what I want to do but yours has helped me the most, by far!

    I’m working on a real-time tracking app and currently, I’m pulling records from a database, checking the user’s location in Google Latitude and looping your addMarker call. This is working as I can see the marker change position on my map when the user’s position changes. The problem is, when the marker moves to the new position, it doesn’t remove the previous position’s marker.

    My main question is, should your code be removing a previous marker when a new one is created? If not, how can I achieve this?

    Thanks!
    Mike

  26. Bogdan Pop says: May 22nd, 2012 at 7:54 am

    Hi Michael,

    The markers are added to the array and are kept in there as long as you want them. So if you’re not removing the old marker it will still show up on the map.

    However, based on your comment I think that you’re adding a new marker with the new position instead of changing its position.

    If you want to change the position of a marker, you should pull it out from the array unless you already have it in a variable (IE: you only have 1 marker on the map) and use setPosition(latlng:LatLng) method to change the position. This way you won’t be creating a new marker, you’d only be changing the position.

  27. Michael says: May 22nd, 2012 at 6:31 pm

    Thanks for the reply!

    You are correct, I am adding a new marker and not changing the original’s position. I see how I’d rather be changing the position instead of adding a new. The part I liked about your code was the duplicate checking when adding. I was originally having that problem too. :-)

    This is all pretty new to me! Do you think you could code up an example that fits your original code, for pulling the proper item from the array and using it with a setPosition method? I’d really appreciate it!

    Mike

  28. Michael says: May 24th, 2012 at 9:47 pm

    Hey Bogdan,

    Still working through this and seeing something I can’t explain. When feeding the Longitude “-112.0978698″ into the addMarker function and then reading the array variable back I’m getting “-112.09786980000001″. Can you explain why this is happening? Also, the value of the “position” key in the array seems to output with () around it. Is this normal?

    Thx!
    Mike

  29. 23 Best jQuery Google Maps Plugins - Baqar Abbas says: February 17th, 2013 at 12:05 pm

    […] Build a POI map using jQuery Google Maps v3 […]

  30. 23 Best jQuery Google Maps Plugins - Dg3World says: February 17th, 2013 at 12:05 pm

    […] Build a POI map using jQuery Google Maps v3 […]

  31. 30+ Useful jQuery Google Maps Plugins | A Pressed World says: May 22nd, 2013 at 5:16 am

    […] Build a POI map using jQuery & Google Maps v3 (revised) by Bogdan Pop – MORE INFO […]

  32. 20 Useful Google Maps jQuery Plugins says: October 15th, 2013 at 2:25 pm

    […] Build a POI map using jQuery & Google Maps v3 […]

  33. 20+ Useful jQuery Google Maps Plugins | Web Revisions says: May 31st, 2014 at 10:39 am

    […] POI map […]

  34. 20+ Useful jQuery Google Maps Plugins says: June 3rd, 2014 at 7:37 am

    […] POI map […]





Save time next time! You won't have to fill out all these fields again. Register in just a few clicks and then login.


If you do not have a username, you can register in just a few clicks.