Google Maps API 3 – Markers

Markers are the perfect way to put places of interest on a map and that’s probably one of the most used features in digital maps. In this article, which is the third in a series about Google Maps API 3, I will show you how to use them in Google Maps API 3.

If you aren’t already familiar with the map object, I recommend that you first read the two previous articles in this series.

The marker object

The marker object resides in the google.maps.Marker namespace and takes a single argument, options. Options is an object literal called Marker options that can have several properties of which two are required:

  • map [Map]
    Map is a reference to the map where you want to add the marker.
  • position [LatLng]
    This property indicates the position of the marker and is of type google.maps.LatLng

Lets start by creating a map and adding a regular marker with the standard look and behavior. If you’ve read the prior articles in this series you should already be familiar with the code that creates the map. Please note that I’ve used a somewhat more compact syntax here than in previous examples.

// Creating a map
var map = new google.maps.Map(document.getElementById('map'), {  
  zoom: 7,
  center: new google.maps.LatLng(56.83, 15.16),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

// Creating a marker and positioning it on the map
var marker = new google.maps.Marker({
  position: new google.maps.LatLng(56.8848, 14.7730), 
  map: map
});

This code would result in a marker being added to the map, incidentally marking the place where I work. Note that the marker is immediately added to the map upon creation. So there’s no need, like in the old API, to explicitly add it to the map after it has been created.

Adding a tooltip

A common thing one might want to do is to add a tooltip to the marker. The tooltip is displayed when a user hovers with the mouse pointer over the marker. This is easily done by adding the property title to the marker options object.

Since this marker won’t be clickable I want to somehow indicate this. That is done by setting the property clickable to false. This results in that the mouse cursor won’t change on hover.

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(56.8848, 14.7730),
  map: map,
  title: 'My workplace',
  clickable: false
});

Here’s how this will look like on the map.

Definition

  • title [string]
    Sets the tooltip of the marker.
  • clickable [boolean]
    Defines whether the marker is clickable/draggable or not. If set to false it will not display a special mouse cursor on hover. Default value is true.

Changing the default marker icon

Often we want to use a different marker than the default one. The API offers a simple way of doing this with the property icon. Icontakes either an URL pointing to an image or a MarkerIcon as its value. In this example I will use the more simpler, URL, and point it to this image.

This icon is taken from Nicolas Mollet’s map icon set at http://mapicons.nicolasmollet.com. There’s lots of similar icons that you can use.

Here’s the code for creating a marker with a custom marker icon.

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(56.8848, 14.7730), 
  map: map,
  title: 'My workplace',
  clickable: false,
  icon: 'http://google-maps-icons.googlecode.com/files/factory.png'
});

Now the map and the marker will look like this:

There are some other properties for more advanced control of the marker icon, such as shadow and shape. Shadow defines the shadow cast by the icon and shape defines the clickable/draggable area of the marker but I will not explain them further in this article.

Definition

  • icon [string|MarkerImage]
    Defines the marker icon. It can either be an URL pointing to a suitable image or an object of type MarkerImage.
  • shadow [string|MarkerImage]
    Sets the shadow of a marker icon. Takes either an URL or a MarkerImage as its value.
  • shape [object]
    Defines the clickable/draggable area of a marker. It takes an object as its value. The object contains coordinates that define a polygon much the same way an imageMap is defined.
  • flat [boolean]
    If set to true disables the shadow of the marker.

Note: By explicitly setting icon, the property shadow is reset. So even if we don’t provide shadow with a value, it will not inherit the shadow of the default marker. I could be argued that in this case the property flat should be set to true, but it’s not necessary for the marker to not have a shadow.

Other properties

Additionally there are a few other properties you can use to control the marker.

  • cursor [string]
    This property changes the way the cursor look when the mouse pointer hovers over the marker.
  • visible [boolean]
    This property determains if the marker should be visible or not. Set it to false to make the marker invisible. The default value is true.
  • zIndex [number]
    Sets the stack order of markers. Could be handy if several markers sits on top of each other.

Live demo

Be sure to checkout the Live Demo to see the code shown in this article in action.

Other resources

For a full and most recent definition of the marker object check out the API reference. Also check out the section about overlays in the documentation.

My Google Maps book

If you found this article useful you might be interested in my book Beginning Google Maps API 3. It covers everything you need to know to create awesome maps on your web sites. Buy it on Amazon.com

About the author

Gabriel Svennerberg is an UX Designer and FrontEnd Developer living in Sweden. When he's not busy designing or building applications at Meetod, he writes about UX Design and all things web on In usability we trust. Gabriel is the author of the book Beginning Google Maps API 3 published by Apress. Gabriel on Google+
  • http://code.google.com/p/google-maps-icons/ Nico Mollet

    Hello Gabriel, I am Nicolas Mollet creator of Google maps icons project (http://code.google.com/p/google-maps-icons/)

    Thanks for the backlink.
    Do you know any public maps (your maps ?) that use this icon collection. I am creating a list of sites using thoses icons.

    You may help me on something else.
    I am desperate to find how to use GM Api 3 with something like :

    position: new google.maps.Address(123, Rocking Street, New York, USA),

    There are places I don’t know the latitude&longitude. How can I pass the full address to the API ?
    All the tutorials I find work with the coordinates, that I don’t have…
    Thanks if you can help.

  • Gabriel Svennerberg

    Hi Nicolas,

    No I’m afraid I don’t know of any sites that uses your icons. I will however, probably use them in a few examples in my upcoming book, where I of course will give you credit. I really like them and it’s nice to see that the collection is growing. Good job!

    When it comes to getting the coordinates for an address, you need to use the GeoCoding Service. Check out the documentation to see how it’s used.

    • Kevin

      Thank you for this documentation!

  • trisna

    Hello everybody ,I am a php programmer
    can you help me out by giving me a script of google map in which it will point multiple addresess dynamically.

  • Lorenzo

    Hello Gabriel, I am Lorenzo Emanuelli; tnx for this very useful blog. I have a little problem: Google Maps Api 3 work very well on firefox for windows and mac, but on ie7 i can’t view the map, using the same code ! Have you an idea of which problem coluld be?
    Tnx for your attention.

    Lorenzo

  • http://www.thegrowingvine.com Nancy B

    Thank you so much for this. Like Lorenzo I had trouble with IE7 then I looked at the page source on your example and realized I had some mistakes in the javascript which I corrected. Hope that helps Lorenzo.

    My site is focused on New England vineyards – I am trying to raise awareness and get people to visit them. The maps are very important, and with your help Gabriel, I can now put tooltips and other options.

    As a graphic designer being able to follow your examples is great!
    — Nancy

  • http://dealbit.com/ atkins

    how to add multiple markers without separate entries like:


    marker1 = new google.maps.Marker({ position: latlng1, map: myMap, title:'wdw' });
    marker2 = new google.maps.Marker({ position: latlng2, map: myMap, title:'wdw' });

  • Than Polas

    Hello Gabriel,
    Do you have a solution for v3 to automatically adjust the zoom level so that it includes all the markers displayed?

    e.g. i have multiple markers scattered on a map and i have to decide which zoom level to use… how can i do that in v3?

    Thankyou

  • http://www.svennerberg.com Gabriel Svennerberg

    Than Polas: You can use the LatLngBounds object for this. Simply extend it with the LatLng of each marker you add to the map and then call the fitBounds() method of the map object and pass it the LatLngBounds object.

    Assuming that myPositions is an array containing LatLng objects this is how it’s done:

    // Create a LatLngBounds object
    var bounds = new google.maps.LatLngBounds();
    
    for (var i = 0; i < myPositions.lenght; i++) {
      // Insert code to add marker to map here
    
      // Extend the LatLngBound object
      bounds.extend(myPositions[i]);
    }
    map.fitBounds(bounds);
    

    I hope that helps!

  • Daniel

    Hello Gabriel,

    I am trying to incrust text (API v3) in the marks example, will be welcome any suggestions that you could give me in this topic.

    And congratulations for this tutorial so practical and easy to deal

    In advance thank you,

    Regards.

  • Andy Clark

    Hi Gabriel

    Nice articles on API 3. Have you come across any examples of using API 3 with ASP.NET 3.5? The sample javascript executes without errors but nothing is displayed. The HTML examples work OK and as far as I can see the ASP.NET renders the HTML in the same way.

    I don’t want to bother you unnecessarily but I can post some examples if you’re interested.

    Many thanks

    Andy

  • http://www.svennerberg.com Gabriel Svennerberg

    Andy Clark: Hi Andy and thanks!

    I haven’t seen any examples using ASP.NET 3.5 but that shouldn’t make any difference.

    Make sure that you have dimensions set for the containing element of the map. In my examples it’s called <div id="map"></div>. Set its dimensions in your stylesheet like this:

    #map {
      width: 600px;
      height: 400px;
    }
    

    If that’s not the problem, post a link and I will try to take a quick look at it.

  • David S

    Hi,

    Nice article. So far, I haven’t been able to find any API calls in v3 to duplicate the map.clearOverlays() function in v2. Are you aware of any way to remove markers?

    Thanks,
    David

  • http://alegua.com.ar Sandro Franchi

    Hi Gabriel, a question. I’m using MapIconmaker in one of my apps (using API V2.x) just because I need to specify marker colors based in some attribute. I’m willing to migrate to V3, but, is MapIconMaker compatible with V3 or there is any other way (perhaps native) to specify the markers color (and size).

    Thanks in advance,

    Sandro Franchi.

  • http://www.svennerberg.com Gabriel Svennerberg

    David: There’s no clearOverlays() method in v3 so you have to manually keep track of your markers yourself. One way of doing that is to keep them in an array. To remove all the markers from the map you then loop through the array and remove them one by one.

    See the Google Maps API v3 forum for an example on how to do this.

    Sandro: MapIconMaker is currently not available for v3 but I know that at least one person is thinking about porting it to v3. Unfortunately there’s no native way of changing colors or size of the icons in v3 either.

    Check out the thread about MapIconMaker in the Google Maps API v3 forum.

  • Gilles Tanguay

    Hi,

    Is is possible to put miltiple and different markers on a google maps ?? I want to be able to place different markers (like the logo of the company) on the map; every company has a different logo and I want to be able to look at them easily.

    Thanks !

    Gilles

  • http://www.svennerberg.com Gabriel Svennerberg

    Gilles: That’s entirely possible. You just need to create a new MarkerImage for each marker type and pass it as the value for the marker objects icon property. (or just pass an url to the appropriate image to the icon property)

  • Enrico

    Thanks very much Gabriel, it’s long time i was looking such a article so simple and clear!

  • Paul

    Hi Gabriel

    In “my maps” there is an option to display places of interest and then to choose which types of location (coffee shop, gas station, etc) to pinpoint on the map.

    Is there any way of doing this in either V2 or V3? I couldn’t see it when I looked through the docs (but then there are a lot of docs to read). I would find this very useful as our users who have holiday properties to rent could simply enter lat/long of their location into our db and other users (wanting to rent) could see where these kinds of things are.

    Hmmm, “simply”? Is there an API for searching by location, centering the map on an address, clicking on a button and getting an event with lat/long of the map centre?

  • Mike

    Hi.

    Great articles you have provided.

    I am experimenting with adding a tooltip as described but unfortunately it doesn’t appear.
    Is there something wrong with my code ?

    Thanks Mike

    function initialize() {
    var latlng = new google.maps.LatLng(15.6256915, 73.7344704);
    var options = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.HYBRID
    };
    var map = new google.maps.Map(document.getElementById(‘map’), options);

    var marker = new google.maps.Marker({
    position: new google.maps.LatLng(15.6191105, 73.7351704),
    map: map
    });
    var marker = new google.maps.Marker({
    position: new google.maps.LatLng(15.6188521, 73.7347090),
    map: map,
    title: ‘My workplace’,
    clickable: false,
    icon: ‘http://google-maps-icons.googlecode.com/files/factory.png’
    });

    }

  • http://www.svennerberg.com Gabriel Svennerberg

    Mike: After experimenting a bit I found that the property clickable needs to be set to true in order for the title to work.

  • Basti

    Hey Gabriel,

    great Tutorial very clear and simple,

    but i’ve a question, what do you think is the best option do manage a large amount of markers in v3? Can I still use the markermanager or work with xml files?

    And i need to have categories and different zoom levels on my map but i can’t find a helpful tutorial do you have any tips for me?

    Thanks a lot

    Basti

  • http://www.svennerberg.com Gabriel Svennerberg

    Basti: Yes you can still work with MarkerManager and/or XML files. There’s also a utility library called MarkerClusterer that you can use.

    I don’t know of any good tutorial on this for v3 but I’ve just finished a chapter on how to do this using the MarkerManager for my upcoming book. So if you can wait until August you’ll find a tutorial right there. :-) Other than that you can check out the examples in the documentation for MarkerManager.

  • Brendan

    Great explanation. I have a mini-site where you can in put a start-point and an end-point, then Google draws the journey on the map.

    However the default markers are just A and B. I need control over these labels. Any help would be much appreciated?

  • Zwirko

    Is it relatively easy to get a “title” tooltip to display when you load lots of markers from an xml file? I’m struggling with this.

  • Dominic

    Is it possible to have the tooltips of all markers staying on screen all the time without the need to move mouse over them?

  • http://www.svennerberg.com Gabriel Svennerberg

    Dominic: No it’s not. What it does is to attach a title attribute to the html element holding the marker. If you want to have a persistent label you need to use some kind of third party solution. Check out the official utility libraries currently available for v3. Maybe you could use the InfoBox library to do this.

  • mirekh

    Hi

    please, give me an advice in V3.

    I would like to specify a zoom level, which the marker start to be displayed with.

    There was no problem to do that in version 2.
    I did that with

    mm = new GMarkerManager(map, {borderPadding:1});

    mm.addMarker(marker,2,17);

    How do that in V3 ?

  • http://www.svennerberg.com Gabriel Svennerberg

    Mirekh: There’s a v3 compatible version of MarkerManager that you can use to do the exact same thing. Check out MarkerManager at the Google Code repository.

  • http://www.itechians.tk selvaganesan s

    Hi

    How can i remove the markers from map in api 3.Because i have marker overloading problems..please help..

  • Dan

    selvaganesan s: i’ve been just dealing with this problem, you have to store your marks in some variable. Array is ideal for bunch of marks. When you wanna clear them from the map and release from memory, call marker.setMap(null) for each of them.

    var map = new google.maps.Map(element, options);
    var marker = {};

    function addMarker(title, lat, lng) {
    var m = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
    title: title
    });

    marker.push(m);
    }

    function clearMarks() {
    while(m = marker.pop()) {
    m.setMap(null);
    }
    }

  • Wayne Sallee


    20. April 27th, 2010 at 6.31 by Gabriel Svennerberg | Author comment

    Mike: After experimenting a bit I found that the property clickable needs to be set to true in order for the title to work.

    So shouldn’t it be changed to “clickable” in the instructions?

    Wayne Sallee
    Wayne@WayneSallee.com

  • blindfish

    Thanks! This is a really useful article. I’ve now managed to read data from an XML file and display markers based on categories, with options to show and hide each category. I’m currently not using MarkerManager to manage my markers (it didn’t seem to work happily with my code), but instead have added a listener to each marker to determine whether it is displayed at any given zoom level…

    That doesn’t seem entirely efficient to me as I’m assuming that markers that are not visible in the map area at a given zoom level (i.e. they’re off screen) are still using resources. I guess I’ll have to persevere with MarkerManager in order to address this; assuming the map renderer doesn’t handle it?

    I have one question that I haven’t seen addressed anywhere yet: Roughly how many markers can the system handle/display at any one time? From the MarkerManager documentation it sounds like it might be up to 200… Are there any recommended limits we should stick to?

    I’m still at the research stage and don’t know how much data I’m going to be working with, so just want some idea of how lazy I can be with optimisation ;)

  • Billy

    Hi Gabriel I wantt o thank you for this I have been trying to put together the code for a google map that I will be putiing on a site I am working on….I dont know if you can assit hoefully you might…what I am looking to do it place a marker and shadow on map this I can do but having trouble trying to workout to position the shadow to sit evenly behid the main maker I have looked at many tuts but cab seem to get this any help be grateful for a newbie at map making…

  • James

    Thanks Gabriel, so easy to understand. And thank you also for your comment on the fitBounds method – worked a charm

  • hanifa maricar

    Gabriel,

    I’ve just order your book from amazon. I just want to ask you if there is any merit in learning KML. I am using not asp.net and putting up with messy Javascript. Just your opinion.

    Respectfully,

    Hanifa

  • http://www.svennerberg.com Gabriel Svennerberg

    Hanifa: Personally I haven’t been using KML a lot but I suppose it has its benefits, especially if you plan on developing for Google Earth as well. Its just an XML format so it’s really no big deal to learn.

  • shitao

    hello every ,now I want make a Mark with description words besides just like labelMarker in API2
    how to program…

    thanks

    from china

  • shitao

    hello every expert ,now I want make a Mark with description words besides,
    just like labelMarker in API2
    how to program…

    attention:not the property “title”

    thanks

    from china

  • http://www.davidegentilucci.it genti

    Hi,

    i need (would) to display cached (mysql) markers on a map, depending on a range in meters that users can choose.

    Any idea about resolve this?

  • http://www.svennerberg.com Gabriel Svennerberg

    shitao Check out the utility libraries for v3. BothInfoBox and MarkerWithLabel might be of interest for you. google-maps-utility-library-v3.

  • http://www.dound.com David Underhill

    Thanks Gabriel – this is just what I was looking for (but I’d overlooked it in the docs – oops).

  • http://ygamretuta.com Ygam Retuta

    Hi! I have just started reading your book but, so far, have not found a solution in what I’m trying to do. I am trying to duplicate an icon with the following code http://jsbin.com/ijujo3/edit

    however, I can’t get the icon to display using an MarkerImage object. What I want to do is to duplicate the marker icon and scale it then assign it to the babyMarker icon.

    any ideas?

  • http://ygamretuta.com Ygam Retuta

    I have already solve the problem described above regarding duplicating markers. Here is the solution:
    http://www.ygamretuta.com/2011/03/duplicating-and-scaling-an-existing-marker-icon-in-google-maps-v3/

  • http://www.svennerberg.com Gabriel Svennerberg

    Nice job Ygam! I’m sorry I didn’t answered your question in time. One note on your solution. The getIcon() method of the Marker object is documented. Look here in the API documentation.

  • bondeth

    I want to be able search street number and street name in google map api 3.
    So anyone have any idea to do it or some tutorial?
    Thank in advance.

  • http://www.svennerberg.com Gabriel Svennerberg
  • SM

    NOBODY at the entire friggin’ internet has talked about how to create multiple markers and deleting them upon choice.

    If I have three markers and I want to remove, for instance, only the first one with, say rightclick, how the h-k do you do that?

    Me and my friend have been sitting on this problem in v3 for a week now without finding anything. Google sucks when it comes to API:s. Come on, this problem can’t be too hard to foresee.

    Christ, gonna’ do harakiri soon. :-(

  • SM

    I AM AN IDIOT!

    Here is answer to this meticular problem…which wasn’t a problem at all. Gooosh….

    Every marker must have it’s own reference. This reference must be a unique name! Thus can you listen for this special reference when it fires the desired event!
    —–

    function init(){
    var m1_Latlng = new google.maps.LatLng(-25.363882,131.044922);
    var m2_Latlng = new google.maps.LatLng(-22.363882,131.044922);

    var myOptions = {
    zoom: 4,
    center: m1_Latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    }

    var map = new google.maps.Map(document.getElementById(“map_canvas”), myOptions);

    var marker1 = new google.maps.Marker({
    position: m1_Latlng,
    draggable: true,
    title:”Marker 1!”
    });

    var marker2 = new google.maps.Marker({
    position: m2_Latlng,
    draggable: true,
    title:”Marker 2!”
    });

    google.maps.event.addListener(marker1,’rightclick’, function(event){
    marker1.setMap(null);
    });

    google.maps.event.addListener(marker2,’rightclick’, function(event){
    marker2.setMap(null);
    });

    // To add the marker to the map, call setMap();
    marker1.setMap(map);
    marker2.setMap(map);
    }

  • Edward

    Hi! I can’t get the custom marker to display in Chapter 6. What am I doing wrong?

  • http://www.svennerberg.com Gabriel Svennerberg

    Edward: Hard to say. Can you provide a link to your code? You can also download all the examples in the book from the book page, and compare that to what you’ve written yourself.

  • oven lu

    Hi! I am a C# programmer,here is my problem:
    if I Click the marker,I want the map change center,but I want use the LatLng witch is find by marker to set the map center .now I can’t find the LatLng?

  • http://www.svennerberg.com Gabriel Svennerberg

    lu: Here’s one way of doing it:

    google.maps.event.addListener(marker, 'click', function(e) {
      var latLng = e.latLng;
    });
    
  • Edward

    Hi, Thanks for the reply, heres my JS code, no recycle marker/ shadow.

    (function () {
    window.onload = function() {

    var options = {
    zoom: 3,
    center: new google.maps.LatLng(37.09, -95.71),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    };

    var map = new google.maps.Map(document.getElementById(‘map’), options);

    var recycle = new google.maps.MarkerImage(‘img/recycle.png’);
    var shadow = new google.maps.MarkerImage(‘img/shadow.png’);

    var marker = new google.maps.Marker({
    position: new google.maps.LatLng(40.756054, -73.986951),
    map: map,
    icon: recycle,
    shadow: shadow
    });

    };
    }) ();

    Is it something obvious? Thanks again.

  • http://www.svennerberg.com Gabriel Svennerberg

    Edward: Your code looks good except for the trailing comma in the options object. It will make IE choke. But I don’t think that your problem. Check the paths to the images recycle.png and shadow.png. I suspect that these might be wrong.

  • Edward Kemp

    Hi,

    Thanks for your help. Fixed this now. Another question sorry, when creating the random markers for example 9.1 when the map is set to zoom = 3 the centre moves to the middle of Asia for some reason but when I set it to 4 or 5 it centres on the US. Any idea why this may be here is my code.

    (function () {
    window.onload = function() {

    var options = {
    zoom: 3,
    center: new google.maps.LatLng(37.09, -95.71),
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById(‘map’), options);

    google.maps.event.addListenerOnce(map, ‘bounds_changed’, function() {

    var bounds = map.getBounds();

    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();

    var latSpan = northEast.lat() – southWest.lat();
    var lngSpan = northEast.lng() – southWest.lng();

    for (var i = 0; i < 100; i++) {

    var lat = southWest.lat() + latSpan * Math.random();
    var lng = southWest.lng() + lngSpan * Math.random();
    var latlng = new google.maps.LatLng(lat, lng);

    new google.maps.Marker({
    position: latlng,
    map: map
    });
    };

    });
    };
    }) ();

  • theresa v

    I’m trying to add markers from an SQL query. I’m using Coldfusion. I’ve seen the examples with php and xml… is there a way I can access the values in the query without having to write out to xml?

    thanks

  • http://mapicons.nicolasmollet.com Nico Mollet

    I wanted to let everyone know that the map icons site (http://code.google.com/p/google-maps-icons/. ) now has a new dedicated website http://mapicons.nicolasmollet.com.

    * you now have 7 icon styles
    * you can choose you own colors
    * download a group of icons, in a zip file
    * a whole new presentation

  • Pingback: Añadir marcadores a nuestro mapa « Tutorialitos

  • bambuz

    Hello Gabriel,

    I know how to set the title on a marker, but don’t know how to keep the title showing always, instead of showing only when mouse moving above it?

    thanks

    bambuz

  • Pingback: 14?Google???JavaScript??

  • Anonymous

    Hi, Gabriel. Just found this site after I sent you an email. Got your book and learned much from it. I am trying to create a map similar to the example in Chapter 6, p. 126 Listing 6-5, ‘Faking an Axaj Call’. What I need to do is have the data fetched from a mySQL database rather than a web service. I’ve been searching the web and trying to use Ajax and JSON to do it, but have not been successful. If I could see the example of listing 6-5 where it fetches the data from a mySQL database or an array from the mySQL database, I think I could make it work. Thanks in advance. Gary.

  • Pingback: Using Google Map – Javascript Resources

  • Anonymous

    Hi Gabriel! Nice article!

    I would like to ask to you if there’s a way to make the markers a little bigger when the mouse pointer hovers on it.

    Thanks,
    Daniel

    • http://www.svennerberg.com Gabriel Svennerberg

      Hi Daniel.

      Absolutely. It’s entirely possible. You need to attach a mouseover event to the marker and change its icon when it triggers. Then of course you probably want to change it back on the mouseout event. The code to do that looks something like this:


      google.maps.event.addListener(yourMarker, 'mouseover', function(e) {
      yourMarker.setIcon('url/to/bigger/icon/');
      });
      google.maps.event.addListener(yourMarker, 'mouseout', function(e) {
      yourMarker.setIcon('url/to/normal/icon/');
      });

      Cheers,
      Gabriel

      • Anonymous

        Hi Gabriel! Thanks a lot for helping me!

        Could you say where in my html (below) I must insert the code?

        #map_canvas { width: 400px; height: 300px; }

        var map;
        var layer;
        var tableid = 1882479;
        function initialize() {
        map = new google.maps.Map(document.getElementById(‘map_canvas’), {
        center: new google.maps.LatLng(-30.066716983885626, -51.233367919921875),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        layer = new google.maps.FusionTablesLayer(tableid);
        layer.setQuery(“SELECT ‘ENDERECO_GOOGLE’ FROM ” + tableid);
        layer.setMap(map);
        }

        • le

          how can i differentiate between markers added using overlay

  • Chamil512

    You are great!!! Thanks for your script… It was very useful to me…

  • Mandy

    Hi Gabriel, I have a map with several markers and the centre is based on the position of all markers. In some maps, the centre points to a place with no markers. How do I set the map to show the nearest marker when the center of the map has no marker.
    Any help is much appreciated.

  • Antoniu

    Hi Gabriel,

    I am displaying 10 locations on google map using the example with fitbounds.
    My search page is retreiving a list on information thorough ajax/jason call and then I hide the search page and display the list and a map with first then rows locations.
    All is ajax and the page itself is not posted back to the server.
    It works perfect first time, displays all 10 locations on map but after i go back to search page (without posting back, just hide unhide the differen pages on client) and hit search again the map is not displaying again the 10 locations.
    I coudl not find any solution to the issue.

    Code is bellow:

    var arr =[‘red_MarkerA.png’, ‘red_MarkerB.png’, ‘red_MarkerC.png’, ‘red_MarkerD.png’, ‘red_MarkerE.png’, ‘red_MarkerF.png’, ‘red_MarkerG.png’, ‘red_MarkerH.png’, ‘red_MarkerI.png’, ‘red_MarkerJ.png’];

    function initialize(points) {

    var mapObj = null;

    var myOptions = {
    zoom: 11,
    center: new google.maps.LatLng(points[0].Latitude, points[0].Longitude),
    mapTypeControl: true,
    mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    if (“ProviderSearch” == GetSearchType()) {
    mapObj = new google.maps.Map(document.getElementById(“map_canvas”),
    myOptions);
    }
    else if (“HospitalSearch” == GetSearchType()) {
    mapObj = new google.maps.Map(document.getElementById(“mapHospital”),
    myOptions);
    }

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

    //alert(points.length);
    if (points.length > 1) {
    // Add markers to the map
    // Set up three markers with info windows
    var currentAddress = points[0].Address;
    var point = new google.maps.LatLng(points[0].Latitude, points[0].Longitude);
    // var marker = createMarker(point,
    // ” + currentAddress + ‘ Link Map ‘,
    // ‘../../content/images/’ + arr[0]);

    var marker = new google.maps.Marker({
    position: point,
    map: mapObj,
    icon: ‘../../content/images/’ + arr[0]

    //zIndex: Math.round(latlng.lat() * -100000) << 3
    });

    var j = 1;
    //alert('after arr');
    var bounds = new google.maps.LatLngBounds();
    bounds.extend(point);
    //alert('before loop');
    // Add markers to the map with info windows
    for (var i = 0; i < 10 && i < points.length; i++) {

    var lo = points[i].Longitude;
    var la = points[i].Latitude;
    //alert(points[i].Longitude + " " + points[i].Latitude + " " + points[i].FullName);
    var path = '../../content/images/';

    if (currentAddress != points[i].Address) {//alert('i ' + i + ' j ' + j);

    var point = new google.maps.LatLng(la, lo);
    bounds.extend(point);

    var marker = new google.maps.Marker({
    position: point,
    map: mapObj,
    icon: '../../content/images/' + arr[j]

    //zIndex: Math.round(latlng.lat() * -100000) << 3
    });

    j++;
    }
    currentAddress = points[i].Address;
    }
    mapObj.fitBounds(bounds);
    bounds = null;

    }

    }

  • Dyltomkins

    Hi, heres my code, for some reason i cant get the marker to show on the map.

    function initialize() {
    var myLatlng = new google.maps.LatLng(43.76316,6.297913);
    var myOptions = {
    center: myLatlng,
    zoom: 8,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById(“map_canvas”),
    myOptions);
    }
    var marker = new google.maps.Marker({
    position: new google.maps.LatLng(43.76316,6.297913),
    map: map
    });

    // To add the marker to the map, call setMap();
    marker.setMap(map);
    function loadScript() {
    var script = document.createElement(“script”);
    script.type = “text/javascript”;
    script.src = “http://maps.googleapis.com/maps/api/js?key=AIzaSyCuXwBwegl7ja1jxcz2YHPgZUEZHQF-HQw&sensor=false&callback=initialize”;
    document.body.appendChild(script);
    }

    window.onload = loadScript;

  • guns224

    hi could help me!
    I need an example of how to plot coordinates on google maps with a connection from SQL SERVER and ASP.NET.
    I need to show on a single map coordinate all records with information from the records ….
    Thank them eternally.

    Greetings from Salvador

    this is my e-mail: guns224@hotmail.com

  • demarco

    thanks man the syntax for the icon is what i was missing. i didnt know it was like

    ‘http://google-maps-icons.googlecode.com/files/factory.png’

  • Kerenuch

    Hi! Thank you for the article and making yourself available to others. I need to update a link placed within a marker description. Currently, the user selects a location on the map, the marker description (tool tip) appears, and there is a link in the description. How can I access the html code in a marker description? Another way to accomplish what I need would be to be able to toggle between two descriptions for the same marker: one that would have the link and one that would say “no link available”. Thank you in advance for considering the question.

  • angel

    hola, como hacer para que siempre se muestre el tooltip mas no solo cuando pase el mouse sobre el marker ?

  • http://twitter.com/esealtd Ecosystems EA

    how can you add more than one marker?

    • http://www.svennerberg.com Gabriel Svennerberg

      You can just write the same code multiple times. But most of the time you probably want to create several markers from some data format. I’ve written about how to do that in the article Adding multimple markers to google from JSON.

  • Kevin

    Very nice job! This helped me alot! Thank you very much you are a good guy. You make the world a better place! I wish my dad was just like you.