添加标签覆盖Google地图

时间:2015-05-31 06:08:39

标签: google-maps google-maps-api-3 label

我成功添加infowindow

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Google Map Lazy Load</title>    
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script type="text/javascript" src="http://localhost/label/label.js"></script>

        <style>
            #map-canvas{
                width:100%;
                height:500px; 
                position: "absolute"; 
                top: 0px; 
                left: 0px; 
                overflow: "hidden";
            }
        </style>
    </head>
    <body>

        <div id="map-canvas"></div>        
        <script type="text/javascript">
            var map;
            function setMarkers(data) {
                console.log('setMarkers');
                console.log(data);
                var markerJson = JSON.parse(data);

                var pos;
                var marker;
                var allMarkers = [];
                console.log(markerJson.length);
                for (var i = 0; i < markerJson.length; i++) {                    
                    pos = new google.maps.LatLng(markerJson[i].latitude, markerJson[i].longitude);
                    marker = new google.maps.Marker({
                        position: pos,
                        map: map,
                        title: 'Title',
                        icon:'https://www.google.com/support/enterprise/static/geo/cdate/art/dots/red_dot.png'

                    });


                    /// INFO WINDOW //
                    marker['infowindow'] = new google.maps.InfoWindow({
                            content: markerJson[i].no_tiang
                        });

                    var currentinfo = null;

                    google.maps.event.addListener(marker, 'click', function() {
                        if(currentinfo) { currentinfo.close();}
                        this['infowindow'].open(map, this);
                        currentinfo = this['infowindow'];
                    });
                    /// INFO WINDOW //

                    allMarkers.push(marker);
                }
            }

            function fetchMarkers() {
                console.log('fetchMarkers');
                var loaded_markers = ($('#loaded_markers').val() =='') ? 0 : $('#loaded_markers').val();
                var offset = $('#offset').val();
                console.log(loaded_markers + ' - '+ offset);
                $.ajax({
                    type: "GET",
                    url: "lazy_load_ajax.php",
                    data: {
                        start: loaded_markers,
                        offset: offset
                    },                    
                    success: function(data) {
                        //var already_loaded = parseInt(loaded_markers) + parseInt(offset);
                       // $('#loaded_markers').val(already_loaded);
                        setMarkers(data);
                        setTimeout(function(){
                           // fetchMarkers();
                        }, 3000);
                    }
                });
            }

            function initialize() {
                console.log('initialize');
                // Get center
                var map_center = new google.maps.LatLng(0.574853, 123.048032);
                var mapOptions = {
                    zoom: 13,
                    center: map_center,
                    //mapTypeId: google.maps.MapTypeId.HYBRID,
                    panControl: false,
                    streetViewControl: false,
                    mapTypeControl: false
                };
                // Load google map
                map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

                fetchMarkers();
            }

            function loadScript() {                
                var script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' + 'callback=initialize';
                document.body.appendChild(script);
            }
            window.onload = loadScript;
        </script>

    </body>
</html>

现在我想添加标签,但我收到错误,标记只显示1个标记

http://img.ctrlv.in/img/15/05/31/556aa5419dbed.jpg

我在代码infowindow之前添加代码标签

/// LABEL ///
                    var label = new Label({
                       map: map
                     });
                     label.bindTo('position', marker, 'position');
                     label.bindTo('text', marker, 'position');

                     /// LABEL ///

                    /// INFO WINDOW //
                    marker['infowindow'] = new google.maps.InfoWindow({
                            content: markerJson[i].no_tiang
                        });

                    var currentinfo = null;

                    google.maps.event.addListener(marker, 'click', function() {
                        if(currentinfo) { currentinfo.close();}
                        this['infowindow'].open(map, this);
                        currentinfo = this['infowindow'];
                    });
                    /// INFO WINDOW //

script label.js

// Define the overlay, derived from google.maps.OverlayView
function Label(opt_options) {
 // Initialization
 this.setValues(opt_options);

 // Label specific
 var span = this.span_ = document.createElement('span');
 span.style.cssText = 'position: relative; left: -50%; top: -8px; ' +
                      'white-space: nowrap; border: 1px solid blue; ' +
                      'padding: 2px; background-color: white';

 var div = this.div_ = document.createElement('div');
 div.appendChild(span);
 div.style.cssText = 'position: absolute; display: none';
};
Label.prototype = new google.maps.OverlayView;

// Implement onAdd
Label.prototype.onAdd = function() {
 var pane = this.getPanes().overlayLayer;
 pane.appendChild(this.div_);

 // Ensures the label is redrawn if the text or position is changed.
 var me = this;
 this.listeners_ = [
   google.maps.event.addListener(this, 'position_changed',
       function() { me.draw(); }),
   google.maps.event.addListener(this, 'text_changed',
       function() { me.draw(); })
 ];
};

// Implement onRemove
Label.prototype.onRemove = function() {
 this.div_.parentNode.removeChild(this.div_);

 // Label is removed from the map, stop updating its position/text.
 for (var i = 0, I = this.listeners_.length; i < I; ++i) {
   google.maps.event.removeListener(this.listeners_[i]);
 }
};

// Implement draw
Label.prototype.draw = function() {
 var projection = this.getProjection();
 var position = projection.fromLatLngToDivPixel(this.get('position'));

 var div = this.div_;
 div.style.left = position.x + 'px';
 div.style.top = position.y + 'px';
 div.style.display = 'block';

 this.span_.innerHTML = this.get('text').toString();
};

我从这里http://blog.mridey.com/2009/09/label-overlay-example-for-google-maps.html

获得了添加标签的脚本

1 个答案:

答案 0 :(得分:1)

Label javascript取决于您动态加载的Google Maps Javascript API v3。您需要在加载Google Maps Javascript API后加载label.js 。最简单的解决方法是不动态加载它。

working fiddle

代码段

var map;
//0.574853, 123.048032
var data = '[{"id":"1","latitude":"0.57","longitude":"123.04","no_tiang":"stuff for #1"},{"id":"2","latitude":"0.56","longitude":"123.045", "no_tiang":"stuff for #2"}]';

function setMarkers(data) {
  console.log('setMarkers');
  console.log(data);
  var markerJson = JSON.parse(data);

  var pos;
  var marker;
  var allMarkers = [];
  console.log(markerJson.length);
  for (var i = 0; i < markerJson.length; i++) {
    pos = new google.maps.LatLng(markerJson[i].latitude, markerJson[i].longitude);
    marker = new google.maps.Marker({
      position: pos,
      map: map,
      title: 'Title',
      icon: 'https://www.google.com/support/enterprise/static/geo/cdate/art/dots/red_dot.png'

    });

    /// LABEL ///
    var label = new Label({
      map: map,
      text: marker.getPosition().toUrlValue(6)
    });
    label.bindTo('position', marker, 'position');
    // label.bindTo('text', marker, 'position');

    /// LABEL ///

    /// INFO WINDOW //
    marker['infowindow'] = new google.maps.InfoWindow({
      content: markerJson[i].no_tiang
    });

    var currentinfo = null;

    google.maps.event.addListener(marker, 'click', function() {
      if (currentinfo) {
        currentinfo.close();
      }
      this['infowindow'].open(map, this);
      currentinfo = this['infowindow'];
    });
    /// INFO WINDOW //

    allMarkers.push(marker);
  }
}

function fetchMarkers() {
  console.log('fetchMarkers');
  var loaded_markers = ($('#loaded_markers').val() == '') ? 0 : $('#loaded_markers').val();
  var offset = $('#offset').val();
  console.log(loaded_markers + ' - ' + offset);
  /* $.ajax({
                  type: "GET",
                  url: "lazy_load_ajax.php",
                  data: {
                      start: loaded_markers,
                      offset: offset
                  },                    
                  success: function(data) {
                      //var already_loaded = parseInt(loaded_markers) + parseInt(offset);
                     // $('#loaded_markers').val(already_loaded);
                      setMarkers(data);
                      setTimeout(function(){
                         // fetchMarkers();
                      }, 3000);
                  }
              }); */
  setMarkers(data);
}

function initialize() {
  console.log('initialize');
  // Get center
  var map_center = new google.maps.LatLng(0.574853, 123.048032);
  var mapOptions = {
    zoom: 13,
    center: map_center,
    //mapTypeId: google.maps.MapTypeId.HYBRID,
    panControl: false,
    streetViewControl: false,
    mapTypeControl: false
  };
  // Load google map
  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

  fetchMarkers();
}

google.maps.event.addDomListener(window, 'load', initialize);

// Define the overlay, derived from google.maps.OverlayView
function Label(opt_options) {
  // Initialization
  this.setValues(opt_options);

  // Label specific
  var span = this.span_ = document.createElement('span');
  span.style.cssText = 'position: relative; left: -50%; top: -8px; ' +
    'white-space: nowrap; border: 1px solid blue; ' +
    'padding: 2px; background-color: white';

  var div = this.div_ = document.createElement('div');
  div.appendChild(span);
  div.style.cssText = 'position: absolute; display: none';
};
Label.prototype = new google.maps.OverlayView;

// Implement onAdd
Label.prototype.onAdd = function() {
  var pane = this.getPanes().overlayLayer;
  pane.appendChild(this.div_);

  // Ensures the label is redrawn if the text or position is changed.
  var me = this;
  this.listeners_ = [
    google.maps.event.addListener(this, 'position_changed',
      function() {
        me.draw();
      }),
    google.maps.event.addListener(this, 'text_changed',
      function() {
        me.draw();
      })
  ];
};

// Implement onRemove
Label.prototype.onRemove = function() {
  this.div_.parentNode.removeChild(this.div_);

  // Label is removed from the map, stop updating its position/text.
  for (var i = 0, I = this.listeners_.length; i < I; ++i) {
    google.maps.event.removeListener(this.listeners_[i]);
  }
};

// Implement draw
Label.prototype.draw = function() {
  var projection = this.getProjection();
  var position = projection.fromLatLngToDivPixel(this.get('position'));

  var div = this.div_;
  div.style.left = position.x + 'px';
  div.style.top = position.y + 'px';
  div.style.display = 'block';

  this.span_.innerHTML = this.get('text').toString();
};
#map-canvas {
  width: 100%;
  height: 500px;
  position: "absolute";
  top: 0px;
  left: 0px;
  overflow: "hidden";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>