【问题标题】:How can I create numbered map markers in Google Maps V3?如何在 Google Maps V3 中创建编号的地图标记?
【发布时间】:2011-01-27 01:07:56
【问题描述】:

我正在制作一张上面有多个标记的地图。

这些标记使用自定义图标,但我还想在顶部添加数字。我已经看到如何使用旧版本的 API 来实现这一点。如何在 V3 中做到这一点?

*注意——当您将鼠标悬停在标记上时,“title”属性会创建一个工具提示,但我希望即使您没有将鼠标悬停在自定义图像顶部,它也会分层显示。

这是标记类的文档,这些属性似乎都没有帮助:http://code.google.com/apis/maps/documentation/v3/reference.html#MarkerOptions

【问题讨论】:

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


【解决方案1】:
  $(document).ready(function() {
    // initiate Google maps
    initialize();
    // make a .hover event
    $('#markers_info .marker').hover(
      // mouse in
      function () {
        // first we need to know which <div class="marker"></div> we hovered
        var index = $('#markers_info .marker').index(this);
        markers[index].setIcon(highlightedIcon());
      },
      // mouse out
      function () {
        // first we need to know which <div class="marker"></div> we hovered
        var index = $('#markers_info .marker').index(this);
        markers[index].setIcon(activeIcon());
      }

      );
  });
  /**
    Google Maps stuff
    */
    var markerData = [   // the order of these markers must be the same as the <div class="marker"></div> elements
    {lat: 43.0628, lng: -89.4165, title: 'Manneken Pis'},
    {lat: 43.0749, lng: -89.3927, title: 'Jeanneke Pis'},
    {lat: 43.0731, lng: -89.4012, title: 'Grand Place'},
    {lat: 43.0766, lng: -89.4125, title: 'Manneken Pis'},
    {lat: 43.0775, lng: -89.4457, title: 'Jeanneke Pis'},
    {lat: 43.0972, lng: -89.5043, title: 'Grand Place'},
    {lat: 43.1351, lng: -89.4385, title: 'Manneken Pis'},
    {lat: 43.1267, lng: -89.3203, title: 'Jeanneke Pis'}
    ];
    var label = "1";
    var map;
    var markers = [];
    var mapOptions = {
      zoom: 12,
      center: new google.maps.LatLng(43.0731,-89.4360),// United state,madison long lat
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    function initialize() {
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      new google.maps.Size(49,100)
      for (var i=0; i<markerData.length; i++) {
        markers.push(
          new google.maps.Marker({
            position: new google.maps.LatLng(markerData[i].lat, markerData[i].lng),
            title: markerData[i].title,
            map: map,
            label: {
              text: label,
              // Adding the custom label
              fontFamily: 'Raleway, sans-serif' + label,
              color: 'white',
              fontSize: "16px",
              fontweight:"bold"
            },
            icon: activeIcon()
          })
          );
      }
    }
    // functions that return icons.  Make or find your own markers.
    function activeIcon() {
      return {
       path:
       "M172.268 501.67C26.97 291.031 0 269.413 0 192 0 85.961 85.961 0 192 0s192 85.961 192 192c0 77.413-26.97 99.031-172.268 309.67-9.535 13.774-29.93 13.773-39.464 0z",
       fillColor: "#2f8aac",
       fillOpacity: 1,
       strokeWeight: 0,
       rotation: 0,
       scale: 0.08,
       anchor: new google.maps.Point(15, 30),
       labelOrigin: new google.maps.Point(200, 200)

     };
   }

    // functions that return icons.  When hovering at the sidebar.
   function highlightedIcon() {
    return {
      path:
      "M172.268 501.67C26.97 291.031 0 269.413 0 192 0 85.961 85.961 0 192 0s192 85.961 192 192c0 77.413-26.97 99.031-172.268 309.67-9.535 13.774-29.93 13.773-39.464 0z",
      fillColor: "#d22a15",
      fillOpacity: 5,
      strokeWeight: 0,
      rotation: 0,
      scale: 0.12,
      anchor: new google.maps.Point(15, 30),
      labelOrigin: new google.maps.Point(200, 200)
    };
  }

【讨论】:

  • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请编辑您的答案以添加一些解释,包括您所做的假设。
【解决方案2】:

也许有些人仍在寻找这个,但发现 Google 动态图标已弃用,其他地图图标库有点太丑了。

使用 URL 添加一个带有任意数字的简单标记。在使用 Google 我的地图的 Google Drive 中,当使用设置为“数字序列”的地图图层然后在地图上添加标记/点时,它会创建编号图标。

查看源代码,谷歌有自己的通过 URL 实现的方式:

https://mt.google.com/vt/icon/name=icons/onion/SHARED-mymaps-container-bg_4x.png,icons/onion/SHARED-mymaps-container_4x.png,icons/onion/1738-blank-sequence_4x.png&highlight=ff000000,0288D1,ff000000&scale=2.0&color=ffffffff&psize=15&text=56&font=fonts/Roboto-Medium.ttf

Above URL

我没有广泛使用它,但是通过更改“highlight”参数中的十六进制颜色代码(颜色参数不会像您想象的那样改变颜色),“text”值可以设置为任何字符串和你可以制作一个漂亮的圆形图标,里面有任何数字/值。我相信其他参数也可能有用。

这种方法的一个警告,谁知道 Google 什么时候会从世界上删除这个 URL!

【讨论】:

    【解决方案3】:

    最简单的解决方案 - 使用 SVG

    适用于:IE9IE10、FF、Chrome、Safari

    (如果您使用其他浏览器,请“运行代码 sn-p”并发表评论)

    除了 Google Maps API 之外没有外部依赖!

    只要您的图标采用 .svg 格式,这相当 很容易。如果是这种情况,只需添加适当的文本元素并更改其内容以适应您的 JS 需求。

    在您的.svg 代码中添加类似的内容(这是文本“部分”,稍后将使用 JS 进行更改):

    <text id="1" fill="#20539F" font-family="NunitoSans-ExtraBold, Nunito Sans" font-size="18" font-weight="600" letter-spacing=".104" text-anchor="middle" x="50%" y="28">1</text>
    

    示例:(部分复制自@EstevãoLucas)

    重要: 使用正确的&lt;text&gt; 标签属性。注意text-anchor="middle" x="50%" y="28" 哪个中心更长的数字(更多信息:How to place and center text in an SVG rectangle

    使用encodeURIComponent()(这可能确保与IE9和10兼容)

    // Most important part (use output as Google Maps icon)
    function getMarkerIcon(number) {
      // inline your SVG image with number variable
      var svg = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="40" height="40" viewBox="0 0 40 40"> <defs> <rect id="path-1" width="40" height="40"/> <mask id="mask-2" width="40" height="40" x="0" y="0" fill="white"> <use xlink:href="#path-1"/> </mask> </defs> <g id="Page-1" fill="none" fill-rule="evenodd"> <g id="Phone-Portrait---320" transform="translate(-209 -51)"> <g id="Group" transform="translate(209 51)"> <use id="Rectangle" fill="#FFEB3B" stroke="#F44336" stroke-width="4" mask="url(#mask-2)" xlink:href="#path-1"/> <text id="1" fill="#20539F" font-family="NunitoSans-ExtraBold, Nunito Sans" font-size="18" font-weight="600" letter-spacing=".104" text-anchor="middle" x="50%" y="28">' + number + '</text> </g> </g> </g> </svg>';
      // use SVG without base64 see: https://css-tricks.com/probably-dont-base64-svg/
      return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
    }
    
    // Standard Maps API code
    var markers = [
      [1, -14.2350040, -51.9252800],
      [2, -34.028249, 151.157507],
      [3, 39.0119020, -98.4842460],
      [5, 48.8566140, 2.3522220],
      [9, 38.7755940, -9.1353670],
      [12, 12.0733335, 52.8234367],
    ];
    
    function initializeMaps() {
      var myLatLng = {
        lat: -25.363,
        lng: 131.044
      };
    
      var map = new google.maps.Map(document.getElementById('map_canvas'), {
        zoom: 4,
        center: myLatLng
      });
    
      var bounds = new google.maps.LatLngBounds();
    
      markers.forEach(function(point) {
          var pos = new google.maps.LatLng(point[1], point[2]);
    
          new google.maps.Marker({
            position: pos,
            map: map,
            icon: getMarkerIcon(point[0]),         
          });
    
          bounds.extend(pos);
      });
    
      map.fitBounds(bounds);
    }
    
    initializeMaps();
    #map_canvas {
      width: 100%;
      height: 300px;
    }
    <!DOCTYPE html>
    <html>
    
      <head>
        <link rel="stylesheet" href="style.css">
        
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>        
      </head>
    
      <body>
        <div id="map_canvas"></div>
      </body>
      
      <script src="script.js"></script>
    
    </html>

    有关 Google 地图中的内联 SVG 的更多信息:https://robert.katzki.de/posts/inline-svg-as-google-maps-marker

    【讨论】:

      【解决方案4】:

      这现已添加到映射文档中,并且不需要第三方代码。

      你可以结合这两个样本:

      https://developers.google.com/maps/documentation/javascript/examples/marker-labels

      https://developers.google.com/maps/documentation/javascript/examples/icon-simple

      要获得这样的代码:

      var labelIndex = 0;
      var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789';
      
      function initialize() {
        var bangalore = { lat: 12.97, lng: 77.59 };
        var map = new google.maps.Map(document.getElementById('map-canvas'), {
          zoom: 12,
          center: bangalore
        });
      
        // This event listener calls addMarker() when the map is clicked.
        google.maps.event.addListener(map, 'click', function(event) {
          addMarker(event.latLng, map);
        });
      
        // Add a marker at the center of the map.
        addMarker(bangalore, map);
      }
      
      // Adds a marker to the map.
      function addMarker(location, map) {
        // Add the marker at the clicked location, and add the next-available label
        // from the array of alphabetical characters.
        var marker = new google.maps.Marker({
          position: location,
          label: labels[labelIndex],
          map: map,
          icon: 'image.png'
        });
      }
      
      google.maps.event.addDomListener(window, 'load', initialize);
      

      请注意,如果您有超过 35 个标记,则此方法将不起作用,因为标签仅显示第一个字符(使用 A-Z 和 0-9 表示 35)。请投票给Google Maps Issue 以请求取消此限制。

      【讨论】:

      • 'image.png' 不适合我。这张图片来自哪里?谢谢
      • image.png 您自己的图像文件,该文件位于此脚本旁边。如果文件不是本地文件或相对文件,则设置完整的 url,例如yourdomain.com/images/image.png
      • 无论如何我可以加载我的本地图像文件吗?我应该把它放在哪里?非常感谢
      • 你可以把你的图片和这个脚本放在同一个地方,如果你在自己的机器上测试,只需把它放在 html/javascript 文件旁边的文件夹中。
      • 如果 labelIndex > 9 这不起作用。正如文档所述,marker.label 仅显示第一个字符。 (@IYM-14,如果你使用它,你可能会遇到错误)
      【解决方案5】:

      Google 地图第 3 版内置了对标记标签的支持。不再需要生成自己的图像或实现 3rd 方类。 Marker Labels

      【讨论】:

        【解决方案6】:

        我发现了最好的方法。 使用 Snap.svg 创建 svg,然后使用函数 toDataURL() 创建要包含为图标的图形数据。 请注意,我为标记使用了 SlidingMarker 类,它可以让我很好地移动标记。 使用 Snap.svg,您可以创建任何类型的图形,您的地图会看起来很棒。

        var s = Snap(100, 100);
        s.text(50, 50, store.name);
        // Use more graphics here.
        var marker = new SlidingMarker({
          position: {lat: store.lat, lng: store.lng},
          map: $scope.map,
          label: store.name, // you do not need this
          title: store.name, // nor this
          duration: 2000,
          icon: s.toDataURL()
        });
        

        【讨论】:

          【解决方案7】:

          这个怎么样? (2015 年)

          1) 获取自定义标记图像。

          var imageObj = new Image();
              imageObj.src = "/markers/blank_pin.png"; 
          

          2) 在RAM 中创建一个canvas 并在其上绘制此图像

          imageObj.onload = function(){
              var canvas = document.createElement('canvas');
              var context = canvas.getContext("2d");
              context.drawImage(imageObj, 0, 0);
          }
          

          3) 在上面写任何东西

          context.font = "40px Arial";
          context.fillText("54", 17, 55);
          

          4) 从画布中获取原始数据并将其提供给 Google API 而不是 URL

          var image = {
              url: canvas.toDataURL(),
           };
           new google.maps.Marker({
              position: position,
              map: map,
              icon: image
           });
          

          完整代码:

          function addComplexMarker(map, position, label, callback){
              var canvas = document.createElement('canvas');
              var context = canvas.getContext("2d");
              var imageObj = new Image();
              imageObj.src = "/markers/blank_pin.png";
              imageObj.onload = function(){
                  context.drawImage(imageObj, 0, 0);
          
                  //Adjustable parameters
                  context.font = "40px Arial";
                  context.fillText(label, 17, 55);
                  //End
          
                  var image = {
                      url: canvas.toDataURL(),
                      size: new google.maps.Size(80, 104),
                      origin: new google.maps.Point(0,0),
                      anchor: new google.maps.Point(40, 104)
                  };
                  // the clickable region of the icon.
                  var shape = {
                      coords: [1, 1, 1, 104, 80, 104, 80 , 1],
                      type: 'poly'
                  };
                  var marker = new google.maps.Marker({
                      position: position,
                      map: map,
                      labelAnchor: new google.maps.Point(3, 30),
                      icon: image,
                      shape: shape,
                      zIndex: 9999
                  });
                  callback && callback(marker)
              };
          });
          

          【讨论】:

          • 这是一个很好的解决方案,但我必须补充一点,使用 imageObj.onload 是异步的,并且可能会在循环中导致一些问题。一种解决方法是将 png 加载到浏览器中并使用开发人员工具选择图像数据(使用 Ctrl A)。然后只需将 imageObj.src 设置为 "data:image/png;base64,paste_the_really_long_image_data_string_here";这种方式可以避免使用onload函数,而且速度更快。
          • 性能怎么样?它将如何在有 200 个标记的地图上运行?
          【解决方案8】:

          我使用类似于@ZuzEL 的解决方案做到了这一点。

          不使用默认解决方案 (http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000),您可以使用 JavaScript 随意创建这些图像,无需任何服务器端代码。

          Google google.maps.Marker 接受 Base64 作为其图标属性。有了这个,我们可以从 SVG 创建一个有效的 Base64。

          您可以在此 Plunker 中看到生成与此图像相同的代码:http://plnkr.co/edit/jep5mVN3DsVRgtlz1GGQ?p=preview

          var markers = [
            [1002, -14.2350040, -51.9252800],
            [2000, -34.028249, 151.157507],
            [123, 39.0119020, -98.4842460],
            [50, 48.8566140, 2.3522220],
            [22, 38.7755940, -9.1353670],
            [12, 12.0733335, 52.8234367],
          ];
          
          function initializeMaps() {
            var myLatLng = {
              lat: -25.363,
              lng: 131.044
            };
          
            var map = new google.maps.Map(document.getElementById('map_canvas'), {
              zoom: 4,
              center: myLatLng
            });
          
            var bounds = new google.maps.LatLngBounds();
          
            markers.forEach(function(point) {
              generateIcon(point[0], function(src) {
                var pos = new google.maps.LatLng(point[1], point[2]);
          
                bounds.extend(pos);
          
                new google.maps.Marker({
                  position: pos,
                  map: map,
                  icon: src
                });
              });
            });
          
            map.fitBounds(bounds);
          }
          
          var generateIconCache = {};
          
          function generateIcon(number, callback) {
            if (generateIconCache[number] !== undefined) {
              callback(generateIconCache[number]);
            }
          
            var fontSize = 16,
              imageWidth = imageHeight = 35;
          
            if (number >= 1000) {
              fontSize = 10;
              imageWidth = imageHeight = 55;
            } else if (number < 1000 && number > 100) {
              fontSize = 14;
              imageWidth = imageHeight = 45;
            }
          
            var svg = d3.select(document.createElement('div')).append('svg')
              .attr('viewBox', '0 0 54.4 54.4')
              .append('g')
          
            var circles = svg.append('circle')
              .attr('cx', '27.2')
              .attr('cy', '27.2')
              .attr('r', '21.2')
              .style('fill', '#2063C6');
          
            var path = svg.append('path')
              .attr('d', 'M27.2,0C12.2,0,0,12.2,0,27.2s12.2,27.2,27.2,27.2s27.2-12.2,27.2-27.2S42.2,0,27.2,0z M6,27.2 C6,15.5,15.5,6,27.2,6s21.2,9.5,21.2,21.2c0,11.7-9.5,21.2-21.2,21.2S6,38.9,6,27.2z')
              .attr('fill', '#FFFFFF');
          
            var text = svg.append('text')
              .attr('dx', 27)
              .attr('dy', 32)
              .attr('text-anchor', 'middle')
              .attr('style', 'font-size:' + fontSize + 'px; fill: #FFFFFF; font-family: Arial, Verdana; font-weight: bold')
              .text(number);
          
            var svgNode = svg.node().parentNode.cloneNode(true),
              image = new Image();
          
            d3.select(svgNode).select('clippath').remove();
          
            var xmlSource = (new XMLSerializer()).serializeToString(svgNode);
          
            image.onload = (function(imageWidth, imageHeight) {
              var canvas = document.createElement('canvas'),
                context = canvas.getContext('2d'),
                dataURL;
          
              d3.select(canvas)
                .attr('width', imageWidth)
                .attr('height', imageHeight);
          
              context.drawImage(image, 0, 0, imageWidth, imageHeight);
          
              dataURL = canvas.toDataURL();
              generateIconCache[number] = dataURL;
          
              callback(dataURL);
            }).bind(this, imageWidth, imageHeight);
          
            image.src = 'data:image/svg+xml;base64,' + btoa(encodeURIComponent(xmlSource).replace(/%([0-9A-F]{2})/g, function(match, p1) {
              return String.fromCharCode('0x' + p1);
            }));
          }
          
          initializeMaps();
          #map_canvas {
            width: 100%;
            height: 300px;
          }
          <!DOCTYPE html>
          <html>
          
            <head>
              <link rel="stylesheet" href="style.css">
              
              <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
              <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
              
            </head>
          
            <body>
              <div id="map_canvas"></div>
            </body>
            
            <script src="script.js"></script>
          
          </html>

          在这个演示中,我使用 D3.js 创建了 SVG,然后将 SVG 转换为 Canvas,因此我可以根据需要调整图像大小,然后从 canvas 的 toDataURL 方法中获取 Base64。

          所有这些演示都是基于我的同事 @thiago-mata 代码。为他点赞。

          【讨论】:

          • 谢谢。这在 Firefox 中不起作用,我在 plnkr.co/edit/CiHVNYGXRqa8pHhy4eDY?p=preview 中修复了这个问题 - 需要在 d3 svg 处定义宽度和高度。
          • @estevao_lucas 或 @Arie 解决方案在 IE11 中都不起作用。 “SecurityError”上线:dataURL = canvas.toDataURL();
          • 你是对的。我个人最终使用了不同的方法。我只是在自定义标记上放置了一个带有背景图像的 div:developers.google.com/maps/documentation/javascript/…
          • 添加一个 52kb 的 js 文件只是为了添加地图标记......耶稣
          【解决方案9】:

          以下是具有更新“视觉刷新”样式的自定义图标,您可以通过简单的 .vbs 脚本快速生成这些图标。我还包括一个大型预生成集,您可以立即使用它并使用多种颜色选项:https://github.com/Concept211/Google-Maps-Markers

          链接到 GitHub 托管的图像文件时使用以下格式:

          https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_[color][character].png
          

          颜色
          红、黑、蓝、绿、灰、橙、紫、白、黄

          角色
          A-Z, 1-100, !, @, $, +, -, =, (%23 = #), (%25 = %), (%26 = &), (空白 = •)

          示例:

          https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_red1.png

          https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_blue2.png

          https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_green3.png

          【讨论】:

            【解决方案10】:

            您可以在 google-maps-utility-library-v3 中使用 Marker With Label 选项。

            请参考https://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries

            【讨论】:

              【解决方案11】:

              基于@dave1010 答案,但更新了https 链接。

              编号标记:

              https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000
              

              文本标记:

              https://chart.googleapis.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|Marker
              

              【讨论】:

                【解决方案12】:

                您可能希望从本网站提供的来源下载一组带编号的图标:

                那么你应该能够做到以下几点:

                <!DOCTYPE html>
                <html> 
                <head> 
                    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
                    <title>Google Maps Demo</title> 
                    <script type="text/javascript"
                            src="http://maps.google.com/maps/api/js?sensor=false"></script> 
                
                    <script type="text/javascript"> 
                    function initialize() {
                
                      var myOptions = {
                        zoom: 11,
                        center: new google.maps.LatLng(-33.9, 151.2),
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                      }
                
                      var map = new google.maps.Map(document.getElementById("map"), myOptions);
                
                      var locations = [
                        ['Bondi Beach', -33.890542, 151.274856, 4],
                        ['Coogee Beach', -33.923036, 151.259052, 5],
                        ['Cronulla Beach', -34.028249, 151.157507, 3],
                        ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
                        ['Maroubra Beach', -33.950198, 151.259302, 1]
                      ];
                
                      for (var i = 0; i < locations.length; i++) {
                          var image = new google.maps.MarkerImage('marker' + i + '.png',
                                      new google.maps.Size(20, 34),
                                      new google.maps.Point(0, 0),
                                      new google.maps.Point(10, 34));
                
                          var location = locations[i];
                          var myLatLng = new google.maps.LatLng(location[1], location[2]);
                          var marker = new google.maps.Marker({
                              position: myLatLng,
                              map: map,
                              icon: image,
                              title: location[0],
                              zIndex: location[3]
                          });
                      }
                    }
                    </script> 
                </head> 
                <body style="margin:0px; padding:0px;" onload="initialize();"> 
                    <div id="map" style="width:400px; height:500px;"></div> 
                </body> 
                </html>
                

                上例截图:

                请注意,您可以轻松地在标记后面添加阴影。您可能需要查看Google Maps API Reference: Complex Markers 上的示例以获取更多信息。

                【讨论】:

                • 我想在顶部添加文字,而不仅仅是使用编号的图像。这可能吗?
                【解决方案13】:

                这就是我在 V3 中的做法:

                我首先加载 google maps api,然后在回调方法 initialize() 中加载 MarkerWithLabel.js 我发现 here:

                function initialize() {
                
                            $.getScript("/js/site/marker/MarkerWithLabel.js#{applicationBean.version}", function(){
                
                            var mapOptions = {
                                zoom: 8,
                                center: new google.maps.LatLng(currentLat, currentLng),
                                mapTypeId: google.maps.MapTypeId.ROADMAP,
                                streetViewControl: false,
                                mapTypeControl: false
                            };
                
                            var map = new google.maps.Map(document.getElementById('mapholder'),
                                    mapOptions);
                
                            var bounds = new google.maps.LatLngBounds();
                
                            for (var i = 0; i &lt; mapData.length; i++) {
                                createMarker(i+1, map, mapData[i]); <!-- MARKERS! -->
                                extendBounds(bounds, mapData[i]);
                            }
                            map.fitBounds(bounds);
                            var maximumZoomLevel = 16;
                            var minimumZoomLevel = 11;
                            var ourZoom = defaultZoomLevel; // default zoom level
                
                            var blistener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
                                if (this.getZoom(map.getBounds) &gt; 16) {
                                    this.setZoom(maximumZoomLevel);
                                }
                                google.maps.event.removeListener(blistener);
                            });
                            });
                        }
                
                        function loadScript() {
                            var script = document.createElement('script');
                            script.type = 'text/javascript';
                            script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&amp;libraries=places&amp;sensor=false&amp;callback=initialize";
                            document.body.appendChild(script);
                        }
                
                        window.onload = loadScript;
                
                    </script> 
                

                然后我使用createMarker() 创建标记:

                function createMarker(number, currentMap, currentMapData) {
                
                   var marker = new MarkerWithLabel({
                       position: new google.maps.LatLng(currentMapData[0], currentMapData[1]),
                                 map: currentMap,
                                 icon: '/img/sticker/empty.png',
                                 shadow: '/img/sticker/bubble_shadow.png',
                                 transparent: '/img/sticker/bubble_transparent.png',
                                 draggable: false,
                                 raiseOnDrag: false,
                                 labelContent: ""+number,
                                 labelAnchor: new google.maps.Point(3, 30),
                                 labelClass: "mapIconLabel", // the CSS class for the label
                                 labelInBackground: false
                                });
                            }
                

                由于我向标记添加了 ma​​pIconLabel 类,因此我可以在我的 css 中添加一些 css 规则:

                .mapIconLabel {
                    font-size: 15px;
                    font-weight: bold;
                    color: #FFFFFF;
                    font-family: 'DINNextRoundedLTProMediumRegular';
                }
                

                结果如下:

                【讨论】:

                • 致多年后发现的人们:google-maps-utility-library-v3.googlecode.com/svn/tags/… 对我认为相同的源代码进行了多次修订。 v1.1.5 对我有用,但 v1.1.9 没有,如果上述方法不起作用,也许尝试旧版本。感谢 Jakob 提供的信息
                • 在使用自定义标签位置向地图添加大量标记时,我遇到了 MarkerWithLabel 问题。
                【解决方案14】:

                不幸的是,这并不容易。您可以基于 OverlayView 类 (an example) 创建您自己的自定义标记,并将您自己的 HTML 放入其中,包括一个计数器。这将为您留下一个非常基本的标记,您无法轻松拖动或添加阴影,但它是非常可定制的。

                或者,您也可以add a label to the default marker。这将不太可定制,但应该可以工作。它还保留了标准标记所做的所有有用的事情。

                您可以在 Google 的文章 Fun with MVC Objects 中阅读有关叠加层的更多信息。

                编辑:如果您不想创建 JavaScript 类,可以使用Google's Chart API。例如:

                编号标记:

                http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000
                

                文本标记:

                http://chart.apis.google.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|foo
                

                这是一种快速简便的方法,但它的可定制性较差,并且需要客户端为每个标记下载一个新图像。

                【讨论】:

                • 使用 Charts API 是我的首选方法。
                • 你有快速创建 1000 个带编号的图标的方法吗?
                • 请注意,Charts API 计划在 2015 年 4 月折旧 - 所以大约需要 6 个月。
                • 您的意思是“已弃用”。否则人们找不到这个词
                • 需要明确的是,整个 Google Carts API 并没有被弃用,只是图像图表和信息图表工具。但正如约翰所提到的,这个答案无论如何都会在 3.21 版本中过时。请参阅约翰的回答。
                【解决方案15】:

                我的两分钱展示了如何使用Google Charts API 来解决这个问题。

                【讨论】:

                • 聪明!我已经有了编号的图像,但我非常喜欢这种方法。
                • 这就是为什么你需要在回答时将代码的解决方案复制到答案框中。
                【解决方案16】:

                如果您有一些编程技能,在服务器端生成带标签的图标是非常可行的。除了 PHP,您还需要服务器上的 GD 库。几年来一直为我工作得很好,但要让图标图像同步确实很棘手。

                我通过 AJAX 发送几个参数来定义空白图标、文本和颜色以及要应用的 bgcolor。这是我的 PHP:

                header("Content-type: image/png");
                //$img_url = "./icons/gen_icon5.php?blank=7&text=BB";
                
                function do_icon ($icon, $text, $color) {
                $im = imagecreatefrompng($icon);
                imageAlphaBlending($im, true);
                imageSaveAlpha($im, true);
                
                $len = strlen($text);
                $p1 = ($len <= 2)? 1:2 ;
                $p2 = ($len <= 2)? 3:2 ;
                $px = (imagesx($im) - 7 * $len) / 2 + $p1;
                $font = 'arial.ttf';
                $contrast = ($color)? imagecolorallocate($im, 255, 255, 255): imagecolorallocate($im, 0, 0, 0); // white on dark?
                
                imagestring($im, $p2, $px, 3, $text, $contrast);    // imagestring  ( $image, $font, $x, $y, $string, $color)
                
                imagepng($im);
                imagedestroy($im);
                }
                $icons =   array("black.png", "blue.png", "green.png", "red.png", "white.png", "yellow.png", "gray.png", "lt_blue.png", "orange.png");      // 1/9/09
                $light =   array( TRUE,         TRUE,       FALSE,       FALSE,     FALSE,      FALSE,      FALSE,          FALSE,      FALSE);     // white text?
                
                $the_icon = $icons[$_GET['blank']];             // 0 thru 8 (note: total 9)
                $the_text = substr($_GET['text'], 0, 3);        // enforce 2-char limit
                do_icon ($the_icon, $the_text,$light[$_GET['blank']] ); 
                

                它通过以下方式在客户端调用: var image_file = "./our_icons/gen_icon.php?blank=" + escape(icons[color]) + "&text=" + iconStr;

                【讨论】:

                • 这实际上并不是一个糟糕的解决方案。在我们的设置中生成每个标记只需要大约 30 毫秒。感谢分享。
                【解决方案17】:

                我没有足够的声誉来评论答案,但想指出 Google Chart API 已被弃用。

                来自API homepage

                谷歌图表工具的信息图表部分已正式发布 自 2012 年 4 月 20 日起已弃用。

                【讨论】:

                • Google Chart API没有被弃用,只有图像图表和信息图表工具。这可能已被 dave1010 的回答所使用,但无论如何,最新的 Google 地图现在为您提供了更好的解决方案(请参阅约翰的回答)。
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2011-07-14
                • 2011-06-16
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多