google map使用自訂Marker在地圖上添加文字標示

來源:互聯網
上載者:User

google map預設的標示GMarker,只能使用圖片不能使用文字。但是在實際中,我們不可避免的需要在地圖上標示文字資訊。例如地名等。Google 地圖 API 使我們可以通過擴充GMarker實現自訂的GMarker的子類LabelMarker。

1 google.maps.LabelMarker = function(latlng, options)
2 {
3     this.latlng = latlng;
4     this.labelText = options.labelText || '';
5     this.labelClass = options.labelClass || 'writeb';
6     this.labelOffset = options.labelOffset || new google.maps.Size(8, -33);
7     options.icon = options.icon || getTextIcon();
8     google.maps.Marker.apply(this, arguments);
9 }
10
11 google.maps.LabelMarker.prototype = new google.maps.Marker(new google.maps.LatLng(0, 0));
12
13 google.maps.LabelMarker.prototype.initialize = function(map){
14     google.maps.Marker.prototype.initialize.call(this, map);
15     
16     var label = document.createElement('div');
17     label.className = this.labelClass;
18     label.innerHTML = this.labelText;
19     label.style.position = 'absolute';
20     label.style.width = '48px';
21     map.getPane(G_MAP_MARKER_PANE).appendChild(label);
22
23     this.map = map;
24     this.label = label;
25 }
26
27 google.maps.LabelMarker.prototype.redraw = function(force){
28     google.maps.Marker.prototype.redraw.call(this, map);
29
30     if(!force)
31     {
32         return;
33     }
34
35     var point = this.map.fromLatLngToDivPixel(this.latlng);
36     var z = google.maps.Overlay.getZIndex(this.latlng.lat());
37     
38     this.label.style.left = (point.x + this.labelOffset.width) + 'px';
39     this.label.style.top = (point.y + this.labelOffset.height) + 'px';
40     this.label.style.zIndex = z + 1;
41 }
42
43 google.maps.LabelMarker.prototype.remove = function(){
44     this.label.parentNode.removeChild(this.label);
45     this.label = null;
46     google.maps.Marker.prototype.remove.call(this);
47 }
48 
49 function getTextIcon()
50 {
51     var icon = new google.maps.Icon();
52     icon.image = "/js/map/img/mapts.gif";
53     icon.iconSize = new GSize(48, 40);
54     icon.iconAnchor = new GPoint(0, 40);
55     icon.infoWindowAnchor = new GPoint(5, 1);
56     return icon;
57 }

在頁面上調用的代碼:

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

現在就會在地圖上顯示我們自訂的GMarker標識了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.