在Google地图上添加DIVS作为叠加标记

时间:2013-04-25 13:57:22

标签: javascript google-maps google-maps-markers

我想知道是否可以在Google地图上添加div作为叠加标记。我试过这个,但它不起作用。

var map = new GMap2(document.getElementById("mapview"));
    map.setCenter(new GLatLng(37.4419, -122.1419), 13);
    map.setUIToDefault();

    var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
    var marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          icon: '<div style="position: absolute; background-color:red; width: 20px; height: 20px;" ></div>',
    });
    marker.setMap(map);

1 个答案:

答案 0 :(得分:1)

试一试。你必须创建自己的自定义Overlay类,扩展谷歌OverlayView,然后你可以随意投入任何你想要的元素。

function DivMarker(latlng,  map, value) {
    this.latlng_ = latlng;
    this.value = value;
    /*Do this or nothing will happen:*/
    this.setMap(map);
}

DivMarker.prototype = new google.maps.OverlayView();
DivMarker.prototype.draw = function() {
    var me = this;
    var div = this.div_;
    if (!div) {
        // Create a overlay text DIV
        div = this.div_ = document.createElement('DIV');
        div.style.border = "none";
        div.style.position = "absolute";
        div.style.paddingLeft = "0px";
        div.style.cursor = 'pointer';

        var span = document.createElement("span");
        span.style.color = "#000000";
        span.style.fontWeight = "bolder";
        span.style.fontSize = "1em";
        span.style.paddingLeft = "0px";
        span.style.position = "absolute";
        span.className = "markerOverlay";
        span.appendChild(document.createTextNode(this.value));
        div.appendChild(span);
        google.maps.event.addDomListener(div, "click", function(event) {
        google.maps.event.trigger(me, "click");
    });

    // Then add the overlay to the DOM
    var panes = this.getPanes();
        panes.overlayImage.appendChild(div);
    }

    // Position the overlay 
    var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
    if (point) {
      div.style.left = point.x + 'px';
      div.style.top = point.y + 'px';
    }
};

DivMarker.prototype.remove = function() {
    // Check if the overlay was on the map and needs to be removed.
    if (this.div_) {    
        this.div_.parentNode.removeChild(this.div_);
        this.div_ = null;
    }
};

DivMarker.prototype.getPosition = function() {
    return this.latlng_;
};

    /* Add the overlay to your map */
var myLatlng = new google.maps.LatLng(44,-73);
var overlay = new DivMarker(myLatlng, map, "I work!");