Adding an onclick event to google.map marker

前端 未结 6 588
说谎
说谎 2020-12-24 02:20

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 mapPro         


        
6条回答
  •  清酒与你
    2020-12-24 02:38

    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

提交回复
热议问题