Adding an onclick event to google.map marker
Asked Answered
K

7

31

I'm stuck trying to figure out a little bit of JS :( I have a google map

var myCenter=new google.maps.LatLng(53, -1.33);

function initialize()
{
var mapProp = {
    center:myCenter,
    zoom: 14,
    draggable: false,
    scrollwheel: false,
    mapTypeId:google.maps.MapTypeId.ROADMAP
};

var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);

var marker=new google.maps.Marker({
    position:myCenter,
    icon:'images/pin.png',
    url: 'http://www.google.com/',
    animation:google.maps.Animation.DROP
});
marker.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);

But I can't seem to hook up the onclick event for the marker url?

I know it has something to do with adding

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

But where ever I put it causes the map to not display or the marker to not display.

Keijo answered 7/6, 2013 at 13:55 Comment(2)
Wheres your infoWindow?Anastigmat
@Alex I don't need an infoWindow. I'm talking about adding a URL click event to the marker (pin). Thanks though. I think Skelly has the answer.Keijo
P
30

Make sure the marker is defined outside of initialize(). Otherwise, it will be undefined if you attempt to assign the click listener outside of initialize().

Also, you may have SAME-ORIGIN issues if you attempt to load url www.google.com, but it should work fine with a local url.

Updated code

var myCenter=new google.maps.LatLng(53, -1.33);

var marker=new google.maps.Marker({
    position:myCenter,
    url: '/',
    animation:google.maps.Animation.DROP
});

function initialize()
{
var mapProp = {
    center:myCenter,
    zoom: 14,
    draggable: false,
    scrollwheel: false,
    mapTypeId:google.maps.MapTypeId.ROADMAP
};

var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);

marker.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(marker, 'click', function() {window.location.href = marker.url;});

Working Demo on Bootply

Pleurisy answered 7/6, 2013 at 14:22 Comment(1)
What if I create markers dynamically via (mapClick) event and want to define 'click' hander for the each inside?Typescript
D
7

This is what I’d use:

var latLng = new google.maps.LatLng(53, -1.33);

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    center: latLng,
    draggable: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    scrollwheel: false,
    zoom: 14
});

var marker = new google.maps.Marker({
    animation: google.maps.Animation.DROP,
    icon: 'images/pin.png',
    map: map,
    position: latLng
});

google.maps.event.addDomListener(marker, 'click', function() {
    window.location.href = 'http://www.google.co.uk/';
});

I’m not sure if you can store a url property with a Marker object.

If you need to display multiple markers (i.e. from an API call) then you can use a for loop like this:

for (var i = 0; i < markers.length; i++) {
    (function(marker) {
        var marker = new google.maps.Marker({
            animation: google.maps.Animation.DROP,
            icon: 'images/pin.png',
            map: map,
            position: market.latLng
        });

        google.maps.event.addDomListener(marker, 'click', function() {
            window.location.href = marker.url;
        });
    })(markers[i]);
}
Devaney answered 7/6, 2013 at 14:14 Comment(0)
J
1
<div id="googleMap" style="width:60%;height:300px;" onclick="placeMarker();"></div>
<script>
    function myMap() {
        var mapProp= {
        center:new google.maps.LatLng(15.28983, 73.95482),
        zoom:5,
        };
        var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
        google.maps.event.addListener(map, 'click', function(event) {
        placeMarker(map, event.latLng);
        });
    }
        function placeMarker(map, location) {
        var marker = new google.maps.Marker({
            position: location,
            map: map
        });         
        var infowindow = new google.maps.InfoWindow({
            content: 'Latitude: ' + location.lat() +
            '<br>Longitude: ' + location.lng()
            
        });
        infowindow.open(map,marker);
        document.getElementById("sitelatitude").value = location.lat();
        document.getElementById("sitelongitude").value = location.lng();
        }
</script>

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API&callback=myMap">
</script>
Jeffiejeffrey answered 20/4, 2023 at 6:49 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Cumulate
W
0

Here's what I've done in the past. The only difference I see between my code and yours is that I set the marker map in the marker options, and you're setting in with marker.setMap(Map);

var marker = new window.google.maps.Marker({
        position: markerPosition,
        map: map,
        draggable: false,
        zIndex: zIndex,
        icon: getNewIcon(markerType != "archive", isBig)
        , animation: markerAnimation
    });


    window.google.maps.event.addListener(marker, 'click', function () {
        // do stuff
    });
Whitelaw answered 7/6, 2013 at 14:1 Comment(0)
A
0

Not sure where your content is but you would need to do the following...

var yourContent = new google.maps.InfoWindow({
    content: 'blah blah'
});

google.maps.event.addListener(marker, 'click', function() {
  yourContent.open(map,marker);
});
Anastigmat answered 7/6, 2013 at 14:8 Comment(0)
H
0
var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
var mapOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: 'Hello World!',
    url: 'http://www.google.com'
});
google.maps.event.addListener(marker, 'click', function () {
    window.location = marker.url;
});

If you go to this page: https://google-developers.appspot.com/maps/documentation/javascript/examples/full/marker-simple

and paste the code above into the console you will see that it works.

I think the problem you have is the following, you need to put this line:

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

inside of your initialize function.

Hawsehole answered 7/6, 2013 at 14:16 Comment(0)
T
0

In my case, I have multiple markers and I wanted to know which marker was clicked. I found following solution on google forum - https://groups.google.com/g/google-maps-js-api-v3/c/cAJrWZWdD-8?pli=1

By Chris Broadfoot (Google Employee)

You can reference the clicked marker with 'this':

google.maps.event.addListener(marker, 'click', markerListener);

function markerListener() { alert(this.getPosition()); // this.setIcon(... }

Throttle answered 18/8, 2020 at 20:27 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.