您的位置:首页 > 编程语言 > Go语言

google map使用自定义Marker在地图上添加文字标示

2012-08-03 17:03 1046 查看
google map默认的标示GMarker,只能使用图片不能使用文字。但是在实际中,我们不可避免的需要在地图上标示文字信息。例如地名等。Google 地图 API 使我们可以通过扩展GMarker实现自定义的GMarker的子类LabelMarker。

Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ 
--> 1 google.maps.LabelMarker = function(latlng, options)
{
this.latlng = latlng;
this.labelText = options.labelText || '';
this.labelClass = options.labelClass || 'writeb';
this.labelOffset = options.labelOffset || new google.maps.Size(8, -33);
options.icon = options.icon || getTextIcon();
google.maps.Marker.apply(this, arguments);
}

google.maps.LabelMarker.prototype = new google.maps.Marker(new google.maps.LatLng(0, 0));

google.maps.LabelMarker.prototype.initialize = function(map){
google.maps.Marker.prototype.initialize.call(this, map);

var label = document.createElement('div');
label.className = this.labelClass;
label.innerHTML = this.labelText;
label.style.position = 'absolute';
label.style.width = '48px';
map.getPane(G_MAP_MARKER_PANE).appendChild(label);

this.map = map;
this.label = label;
}

google.maps.LabelMarker.prototype.redraw = function(force){
google.maps.Marker.prototype.redraw.call(this, map);

if(!force)
{
return;
}

var point = this.map.fromLatLngToDivPixel(this.latlng);
var z = google.maps.Overlay.getZIndex(this.latlng.lat());

this.label.style.left = (point.x + this.labelOffset.width) + 'px';
this.label.style.top = (point.y + this.labelOffset.height) + 'px';
this.label.style.zIndex = z + 1;
}

google.maps.LabelMarker.prototype.remove = function(){
this.label.parentNode.removeChild(this.label);
this.label = null;
google.maps.Marker.prototype.remove.call(this);
}

function getTextIcon()
{
var icon = new google.maps.Icon();
icon.image = "/js/map/img/mapts.gif";
icon.iconSize = new GSize(48, 40);
icon.iconAnchor = new GPoint(0, 40);
icon.infoWindowAnchor = new GPoint(5, 1);
return icon;
}


  在页面上调用的代码:

1 var marker = new google.maps.LabelMarker(map.getCenter(), {
2 labelText:'我在这'
3 });
4
5 map.addOverlay(marker);

  

现在就会在地图上显示我们自定义的GMarker标识了。

继承GOverlay的实现自定义GMarker的方法: google map自定义GMarker的方法二

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: