Adding an onclick event to google.map marker

前端 未结 6 590
说谎
说谎 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:30

    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]);
    }
    

提交回复
热议问题