0

我想知道是否可以在 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);
4

1 回答 1

1

试试这个。您必须创建自己的自定义 Overlay 类来扩展 google 的 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!");
于 2013-12-17T20:49:41.033 回答