Google使用多个字符

时间:2015-09-08 21:04:57

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

我正在尝试将4个字符的标签(例如“A123”)添加到Google地图标记中,该标记具有使用自定义路径定义的宽图标。

var marker = new google.maps.Marker({
  position: latLon,
  label: { text: 'A123' },
  map: map,
  icon: {
    path: 'custom icon path',
    fillColor: '#000000',
    labelOrigin: new google.maps.Point(26.5, 20),
    anchor: new google.maps.Point(26.5, 43)
    scale: 1,
  }
});

marker label API仅限于一个字符,因此在上面的示例中只显示带有“A”的标记。我尝试使用chrome开发人员工具来破解由gmaps创建的html并恢复更长的标签。它显示完美,不需要修改css,所以我只需找到一种方法来恢复谷歌地图剥离的其他标签字符。

我提出Google Maps Issue请求取消此限制。请考虑通过访问上面的链接投票支持Google问题并主演该问题以鼓励Google修复它 - 谢谢!

但与此同时,我是否可以使用一种解决方法来删除一个char限制?

有没有办法可以创建google.maps.Marker的自定义扩展程序来显示更长的标签?

7 个答案:

答案 0 :(得分:47)

您可以将MarkerWithLabel与SVG图标一起使用。

更新:Google Maps Javascript API v3现在原生支持MarkerLabel

中的多个字符

proof of concept fiddle(你没有提供你的图标,所以我做了一个)

注意:this fix处理的重叠标记上的标签存在问题,并在评论中提及robd

代码段

function initMap() {
  var latLng = new google.maps.LatLng(49.47805, -123.84716);
  var homeLatLng = new google.maps.LatLng(49.47805, -123.84716);

  var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 12,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var marker = new MarkerWithLabel({
    position: homeLatLng,
    map: map,
    draggable: true,
    raiseOnDrag: true,
    labelContent: "ABCD",
    labelAnchor: new google.maps.Point(15, 65),
    labelClass: "labels", // the CSS class for the label
    labelInBackground: false,
    icon: pinSymbol('red')
  });

  var iw = new google.maps.InfoWindow({
    content: "Home For Sale"
  });
  google.maps.event.addListener(marker, "click", function(e) {
    iw.open(map, this);
  });
}

function pinSymbol(color) {
  return {
    path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
    fillColor: color,
    fillOpacity: 1,
    strokeColor: '#000',
    strokeWeight: 2,
    scale: 2
  };
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map_canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
.labels {
  color: white;
  background-color: red;
  font-family: "Lucida Grande", "Arial", sans-serif;
  font-size: 10px;
  text-align: center;
  width: 30px;
  white-space: nowrap;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerwithlabel/src/markerwithlabel.js"></script>
<div id="map_canvas" style="height: 400px; width: 100%;"></div>

答案 1 :(得分:24)

首先,感谢代码作者!

我在google搜索时找到了以下链接,它非常简单,效果最好。除非弃用SVG,否则永远不会失败。

https://codepen.io/moistpaint/pen/ywFDe/

这里的代码中有一些js加载错误,但它完全适用于提供的codepen.io链接。

var mapOptions = {
    zoom: 16,
    center: new google.maps.LatLng(-37.808846, 144.963435)
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);


var pinz = [
    {
        'location':{
            'lat' : -37.807817,
            'lon' : 144.958377
        },
        'lable' : 2
    },
    {
        'location':{
            'lat' : -37.807885,
            'lon' : 144.965415
        },
        'lable' : 42
    },
    {
        'location':{
            'lat' : -37.811377,
            'lon' : 144.956596
        },
        'lable' : 87
    },
    {
        'location':{
            'lat' : -37.811293,
            'lon' : 144.962883
        },
        'lable' : 145
    },
    {
        'location':{
            'lat' : -37.808089,
            'lon' : 144.962089
        },
        'lable' : 999
    },
];

 

for(var i = 0; i <= pinz.length; i++){
   var image = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2238%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23808080%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate%2819%2018.5%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + pinz[i].lable + '%3C%2Ftext%3E%3C%2Fsvg%3E';

  
   var myLatLng = new google.maps.LatLng(pinz[i].location.lat, pinz[i].location.lon);
   var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: image
  });
}
html, body, #map-canvas {
  height: 100%;
  margin: 0px;
  padding: 0px
}
<div id="map-canvas"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDtc3qowwB96ObzSu2vvjEoM2pVhZRQNSA&signed_in=true&callback=initMap&libraries=drawing,places"></script>

您只需要对SVG html进行uri编码,并在for循环中的“data:image / svg + xml”之后替换图像变量中的那个。

对于uri编码,您可以使用uri-encoder-decoder

您可以先解码现有的svg代码,以便更好地了解所写内容。

答案 2 :(得分:7)

好的,这是我提出的一个解决方案,它非常混乱。

我使用fontFamily标签属性将完整标签文本放入div中。然后我使用querySelectorAll来匹配生成的样式属性以提取引用并在地图加载后重写标记:

var label = "A123";
var marker = new google.maps.Marker({
  position: latLon,
  label: {
    text: label,
    // Add in the custom label here
    fontFamily: 'Roboto, Arial, sans-serif, custom-label-' + label
  },
  map: map,
  icon: {
    path: 'custom icon path',
    fillColor: '#000000',
    labelOrigin: new google.maps.Point(26.5, 20),
    anchor: new google.maps.Point(26.5, 43), 
    scale: 1
  }
});

google.maps.event.addListener(map, 'idle', function() {
  var labels = document.querySelectorAll("[style*='custom-label']")
  for (var i = 0; i < labels.length; i++) {
    // Retrieve the custom labels and rewrite the tag content
    var matches = labels[i].getAttribute('style').match(/custom-label-(A\d\d\d)/);
    labels[i].innerHTML = matches[1];
  }
});

这看起来很脆弱。有什么方法不那么糟糕吗?

答案 3 :(得分:3)

从API 3.26.10版开始,您可以使用多个字符设置标记标签。解除限制。

试试吧,它有效!

此外,使用MarkerLabel对象而不仅仅是字符串,您可以为外观设置许多属性,如果使用自定义图标,则可以设置labelOrigin属性以重新定位标签。

来源: https://code.google.com/p/gmaps-api-issues/issues/detail?id=8578#c30 (另外,您可以在上面的链接主题中报告有关此问题的任何问题)

答案 4 :(得分:0)

对于任何试图这样做的人

...在2019年,值得注意的是这里no longer exists(正式)引用的一些代码。 Google很久以前就停止了对“ MarkerWithLabel”项目的支持。它最初托管在Google代码here上,现在非正式地托管在Github here上。

但是Google维护了另一个项目,直到2016年,名为"MapLabel"s。这种方法是不同的(可以说是更好的)。您可以创建与标记具有相同来源的单独地图标签对象,而不是在标记本身中添加mapLabel选项。您可以使用marker with label with multiple characters来创建js-marker-label

答案 5 :(得分:0)

您可以更改简单的标记标签CSS,而无需使用任何额外的插件。

$filesCount = count($_FILES['productphotos']['name']); 
        for($i = 0; $i < $filesCount; $i++)
        {               
            $_FILES['file']['name'] = $_FILES['productphotos']['name'][$i];
            $_FILES['file']['type'] = $_FILES['productphotos']['type'][$i];
            $_FILES['file']['tmp_name'] = $_FILES['productphotos']['tmp_name'][$i];
            $_FILES['file']['error'] = $_FILES['productphotos']['error'][$i];
            $_FILES['file']['size'] = $_FILES['productphotos']['size'][$i];

            $testprodpath = './Products/Old/BagShoes/';
            //$uploadPath = './Products/';
            //$uploadPath = base_url().'Products/';
            $config['upload_path'] = $testprodpath;
            $config['allowed_types'] = 'gif|jpg|jpeg|png';
            $config['max_size']    = '5000';    // max_size in kb
            $config['file_name'] = $_FILES['productphotos']['name'][$i];

            $this->upload->initialize($config);

            //load upload library
            $this->load->library('upload', $config);                

            //upload the files
            if($this->upload->do_upload('file'))
            {
               //Get data about the files
                $fileData = $this->upload->data();
                $name_array[] = $fileData['file_name'];
                           } // closes if

            else
            {
              echo $this->upload->display_errors();             
            } //closes else
        }  //closes for loop 

                $content = $this->input->post('content');
                $datatiny['content'] = $content;

                $imagesnames= implode(',', $name_array);

                //Insert file information into the database
           $data2 = array(
              'WZB_ProductCode'=>$this->input->post('productcode'),
              'ProductGrade'=>$this->input->post('productgrade'),
              'WZB_ProductName'=>$this->input->post('productname'),
              'WZB_ProductDescription'=>$datatiny,
              'WZB_QuantityPerUnit'=>$this->input->post('quantityperunity'),
              'WZB_UnitPrice'=>$this->input->post('unitprice'),
              'WZB_ProductOwner'=>$this->input->post('productowner'),
              'WZB_CategoryName'=>$this->input->post('productcategory'),
              'WZB_VerifiedByAgent'=>$this->input->post('verifiedbyagent'),                  
              'ProductPhotoName'=>$imagesnames,
              'Addedby'=>$this->input->post('addedby')
            );

           $this->db->insert('wzb_product', $data2);                       
           $this->session->set_flashdata('Added Successfully','Record  successfully added'); 
     }   //closes if for checking if file input has file is submitted and if file is uploaded

答案 6 :(得分:-1)

这个问题的一个更简单的解决方案是允许字母,数字和单词作为标签,如下代码。更具体地说,代码行以&#34; icon:&#34;开头。任何字符串或变量都可以替换为&#39; k&#39;。

for (i = 0; i < locations.length; i++) 
      { 
      k = i + 1;
      marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),     
      map: map,
      icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + k + '|FF0000|000000'
});

--- locations数组保存lat和long,k是我映射的地址的行号。换句话说,如果我有100个地址来映射我的标记标签将是1到100。