Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to add click event on marker in Google Map?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 126
    Comment on it

    I was facing issue while populating markers and adding click event on them. When the user clicks on a marker I would like it to send the user to different webpage. For example: If marker represents home page, when you click on this marker it will take you to the home page with more information about home page, and if marker represents blog page and user clicks on this marker then it will take you to the blog page .

    Finally got the solution to it:

    In order to resolve it, you will need to attach an event listener to each marker. The click handler can set document.location to the URL of the page you want to go to.

    var marker = new GMarker(location);
    GEvent.addListener(marker, "click", function() {
        window.location = theURL;
    });
    map.addOverlay(marker);

    Since you will probably be adding markers in a loop, you will need to make sure each one gets its own URL. Since closures keep the actual variables they access (not their values), you probably need to put at least addListener code in its own function to create its own scope. Your loop would look kind of like this:

    function createMarker(location, url) {
        var marker = new GMarker(location);
        GEvent.addListener(marker, "click", function() {
            window.location = url;
        });
        return marker;
    }
    
    // Assuming locations is an array of objects with lat, lng, and url properties
    for (var i = 0; i < locations.length; i++) {
        var loc = locations[i];
        map.addOverlay(createMarker(new GLatLng(loc.lat, loc.lng), loc.url));
    }

     

    Alternative way for above is:

    google.maps.event.addListener(marker, "click", function() {
        window.location = url;
    });

     

    All done!

    Thanks for reading the blog.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: