我已经实施了这个问题的公认答案。当我运行 html 文件时,我在 Google 地图标记上书写的文本显示在错误的位置(请参阅图片 error.png)。谁能帮我在标记上准确显示文本?
标记.html
<html><head>
<title> Hi </title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function TxtOverlay(pos, txt, cls, map){
this.pos = pos;
this.txt_ = txt;
this.cls_ = cls;
this.map_ = map;
this.div_ = null;
this.setMap(map);
}
TxtOverlay.prototype = new google.maps.OverlayView();
TxtOverlay.prototype.onAdd = function(){
var div = document.createElement('DIV');
div.className = this.cls_;
div.innerHTML = this.txt_;
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
div.style.left = ( position.x) + 'px';
div.style.top = ( position.y)+ 'px';
var panes = this.getPanes();
panes.floatPane.appendChild(div);
}
TxtOverlay.prototype.draw = function(){
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
var div = this.div_;
div.style.left = ( position.x) + 'px';
div.style.top = ( position.y)+ 'px';
}
TxtOverlay.prototype.onRemove = function(){
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
TxtOverlay.prototype.hide = function(){
if (this.div_) {
this.div_.style.visibility = "hidden";
}
}
TxtOverlay.prototype.show = function(){
if (this.div_) {
this.div_.style.visibility = "visible";
}
}
TxtOverlay.prototype.toggle = function(){
if (this.div_) {
if (this.div_.style.visibility == "hidden") {
this.show();
}
else {
this.hide();
}
}
}
TxtOverlay.prototype.toggleDOM = function(){
if (this.getMap()) {
this.setMap(null);
}
else {
this.setMap(this.map_);
}
}
var map;
function init(){
var latlng = new google.maps.LatLng(37.90695894, -122.07920128);
var myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!",
icon:"./bluepin.PNG"
});
customTxt = "<div>1</div>"
txt = new TxtOverlay(latlng,customTxt,"customBox",map )
}
</script>
<style>
.customBox {
background: AARRGGBB;
border: 1px;
color:#ffffff;
position: relative;
}
</style>
</head>
<body onload="init()">
<div id="map" style="width: 600px; height: 600px;">
</div>
</body>
</html>