javascript 将自定义标记文本添加到 Google 地图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24421805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:45:57  来源:igfitidea点击:

Adding custom marker text to Google Map

javascripthtmlgoogle-mapsgoogle-apimaps

提问by Growler

I'm creating a new website for new law office.

我正在为新的律师事务所创建一个新网站。

I followed Google API for embedding maps. I added their address, but would like to add the name of the firm to the map... You can see in the map, it doesn't capture the name:

我遵循 Google API 来嵌入地图。我添加了他们的地址,但想将公司名称添加到地图中...您可以在地图中看到,它没有捕获名称:

<iframe width="600" height="450" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?key=myapikey&q=883%20Farmington%20Avenue%2C%20Berlin%2C%20CT%2006037%2C%20United%20States"></iframe>

enter image description here

在此处输入图片说明

So, I tried adding a name before the address in the iframe:

因此,我尝试在 iframe 中的地址之前添加一个名称:

q=Jill+Levin+Law,address here...

q=Jill+Levin+Law,address here...

But I'm guessing the keyword Levinpick ups a matching firm, Soulsby & Levin, LLC... even though I haven't changed the address

但是我猜这个关键字会找到Levin一个匹配的公司,Soulsby & Levin, LLC...即使我没有更改地址

<iframe width="600" height="450" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?key=myapikey&q=Jill+Levin+Law,883%20Farmington%20Avenue%2C%20Berlin%2C%20CT%2006037%2C%20United%20States"></iframe>

enter image description here

在此处输入图片说明

Even the Google API itself picks up the wrong one based on the keyword:

甚至 Google API 本身也会根据关键字选择错误的 API:

enter image description here

在此处输入图片说明

How do I:

我如何:

  • Have Google map pick up the correct name of the office
  • If the office name hasn't been defined yet, how can I simply add the text name to the top of the marker?
  • 让谷歌地图选择正确的办公室名称
  • 如果尚未定义办公室名称,我如何简单地将文本名称添加到标记的顶部?

采纳答案by Jo?o Marcos

When you add the marker to the map you can put a title to the marker.

当您将标记添加到地图时,您可以为标记添加标题。

Use this code to do it:

使用此代码来做到这一点:

map.addMarker(new MarkerOptions().title("Office Name"));

回答by Alvin Magalona

Yo can set the Latitudeand Longitudeof your marker and include a Titleon it.

您可以设置标记的纬度经度,并在其上添加标题

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(-25.363882,131.044922),
    map: map,
    title: 'Our Office'
});

回答by Chien_Khmt

I have the lively sample for this

我有这个活泼的样本

var map;
var root;
var geocoder;
var root_content= 'Type: [type]<BR>IP: 192.168.10.25<BR>Address: [address]';
function initialize() {
    geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'address': 'Ha noi, Vietnam'}, function(results, status) {
    root = results[0].geometry.location;
   
   var myStyles =[
   
       {
         featureType: "administrative",
         elementType: "labels",
         stylers: [
           { visibility: "off" }
         ]
       },{
         featureType: "poi",
         elementType: "labels",
         stylers: [
           { visibility: "off" }
         ]
       },{
         featureType: "water",
         elementType: "labels",
         stylers: [
           { visibility: "off" }
         ]
       }
     
];
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: root,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      streetViewControl: false, styles: myStyles,
     disableDefaultUI: true, scrollwheel: false,
      zoomControl: false, disableDoubleClickZoom: true
    }); 
    
    
    var center = {latLng: root, style: 'ae', content: 'md'};
try{
    Draw();
}catch(e){alert(e)}
     var zoomControlDiv = document.createElement('div');
  var zoomControl = new ZoomControl(zoomControlDiv, map);

  zoomControlDiv.index = 1;
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(zoomControlDiv);
    
    
    
   
   });
}
function ZoomControl(controlDiv, map) {
  
  // Creating divs & styles for custom zoom control
  controlDiv.style.padding = '5px';

  // Set CSS for the control wrapper
  var controlWrapper = document.createElement('div');
//  controlWrapper.style.background = 'white';
  controlWrapper.style.borderStyle = 'solid';
  controlWrapper.style.borderColor = 'gray';
  controlWrapper.style.borderWidth = '1px';
  controlWrapper.style.cursor = 'pointer';
  controlWrapper.style.textAlign = 'center';
  controlWrapper.style.width = '32px'; 
  controlWrapper.style.height = '100px';
  controlDiv.appendChild(controlWrapper);
  
  // Set CSS for the zoomIn
  var zoomInButton = document.createElement('div');
  zoomInButton.innerHTML = '<br><img src="https://i.stack.imgur.com/2k0UD.png" title="Zoom In">';
  controlWrapper.appendChild(zoomInButton);
    
  // Set CSS for the zoomOut
  var zoomOutButton = document.createElement('div');
  zoomOutButton.innerHTML = '<img src="https://i.stack.imgur.com/zPVFs.png" title="Zoom Out">';
  controlWrapper.appendChild(zoomOutButton);
  
   var removeLineButton = document.createElement('div');
  removeLineButton.innerHTML = '<img src="https://i.stack.imgur.com/tAc0f.png" title="Hide Line">';
  controlWrapper.appendChild(removeLineButton);

  // Setup the click event listener - zoomIn
  google.maps.event.addDomListener(zoomInButton, 'click', function() {
  Clean();
    map.setZoom(map.getZoom() + 1);
 Draw();
  });
     google.maps.event.addDomListener(zoomOutButton, 'click', function() {
 Clean();
    map.setZoom(map.getZoom() - 1);
 Draw();
  });  
  
  google.maps.event.addDomListener(removeLineButton, 'click', function() {
   for(var i=0; i<po.length; i++) {
      po[i].setMap(x?map:null);
     
     }
     
     x=x?false:true;
     removeLineButton.innerHTML=x? 
     '<img src="https://i.stack.imgur.com/LeM4f.png" title="Show line">'
     :'<img src="https://i.stack.imgur.com/tAc0f.png" title="Hide line">';
   
  });  
    
}
var x = false;
var po  = [];
var nd  = [];
function Draw1() {
 for(var i=0; i<po.length; i++) {
      po[i].setMap(null);
     
     }
     for(var i=0; i<nd.length; i++) {
      nd[i].remove();
      
     }
     nd=[];
     po=[];
}

function GetData() {
 
}

function Draw1() {
/*
 var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
 var contact = JSON.parse(jsontext);

 contact=JSON.parse
 alert(contact.firstname);
*/
 for(var i=0; i<node.length; i++) {
  //nd.push(create_node(map, node[i]));
 }
 for(var i=0; i<line.length; i++) {
  //po.push(connect_node(map, line.node1, line.node2));
 }
}

function Clean() {
 for(var i=0; i<po.length; i++) {
  po[i].setMap(null);
 }
 for(var i=0; i<nd.length; i++) {
  nd[i].setMap(null);
 }
 po = [];
 nd = [];
}

function Draw() {
    var cen= root;
    var a  =  true;
    var b  = true;
    var dis = 0.1;
    var k  = 0;
    
    for(var i=0; i<10; i++) {
     k++;
     if(a) {
      cen = new google.maps.LatLng(cen.lat()+dis, cen.lng());
      a=false;
     }
     else {
      cen = new google.maps.LatLng(cen.lat(), cen.lng()+dis);
      a=true;
     }
     var style = 'in';
     if(k%5==1) style='ae';
     else if(k%5==2) style='adn';
     else if(k%5==3) style='mn';
     else if(k%5==4) style='asn';
     
     var cur = {latLng: cen, style: style,  content: style.toUpperCase()};
     nd.push(create_node(map, cur));
     for(var j=i+1; j<10; j++) {
      k++;
      if(a) {
      cen = new google.maps.LatLng(cen.lat()+((j%2)==0?1:(-1))*dis, cen.lng());
      a=false;
     }
     else {
      cen = new google.maps.LatLng(cen.lat(), cen.lng()+((j%2)==0?1:(-1))*dis);
      a=true;
     }
     var style = 'in';
     if(k%5==1) style='ae';
     else if(k%5==2) style='asn';
     else if(k%5==3) style='mn';
     else if(k%5==4) style='adn';
      var sub = {latLng: cen, style: style,  content: style.toUpperCase()};
    
      po.push(connect_node(map, cur, sub));
      
      nd.push(create_node(map, sub));
     }
    }
    
}
google.maps.event.addDomListener(window, 'load', initialize);



function CustomMarker(latlng, map, args) {
 this.latlng = latlng; 
 this.args = args; 
 this.setMap(map); 
}
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.draw = function() {
 
 var self = this;
 var div = this.div;
 if (!div) {
  div = this.div = document.createElement('div');
  var style = '';
  var content = '';
  if (typeof(self.args.marker_style) !== 'undefined') {
   style = self.args.marker_style;
   div.className = 'iot-node-'+style;   
  }
  

  if (typeof(self.args.marker_content) !== 'undefined') {
   content = self.args.marker_content;
   var a = document.createElement('a');
  
   a.innerHTML = content;
   div.appendChild(a);
   if(style=='info') {
    var span =  document.createElement('span');
   
    span.innerHTML = 'x';
    google.maps.event.addDomListener(span, "click", function(event) {
     me.remove();
    });
    
    a.appendChild(span);
   }
   
  }
  if (typeof(self.args.marker_style) !== 'undefined' && style!='') {
    var cur = this.getPosition();
    var me  = this;
    
    var panes = this.getPanes();
    panes.overlayImage.appendChild(div);
    var point = this.getProjection().fromLatLngToDivPixel(this.getPosition());
    if (point) {
     if(style!='info') {
      div.style.left = (point.x-10 ) + 'px';
      div.style.top  = (point.y-10)  + 'px';
      google.maps.event.addDomListener(div, "click", function(event) {
       geocoder.geocode({'latLng': cur}, function(results, status) {
        
          var addr = 'null';
          if (status === google.maps.GeocoderStatus.OK) {
            if (results[1]) {
           addr = results[1].formatted_address;
            }
          }
       var sub = {latLng: cur, style: 'info',  content: root_content.replace('[type]', style.toUpperCase()).replace('[address]', addr)};
         nd.push(create_node(map, sub));
        
        
        
        
        
         });
      });

     
     } else {
      
      div.style.left = (point.x-40 ) + 'px';
      div.style.top  = (point.y-15 -div.offsetHeight )  + 'px';
      
     }
    }
  }
  
 }
};
CustomMarker.prototype.remove = function() {
 
 if (this.div) {
  this.div.parentNode.removeChild(this.div);
  this.div = null;
 } 
 this.setMap(null);
 
};
CustomMarker.prototype.getPosition = function() {
 return this.latlng; 
};

function create_node(map, node) {
 return new CustomMarker(
  node.latLng, 
  map,
  {
   marker_style: node.style,
   marker_content: node.content
  }
 );
}



var color= {};
color['ae'] = '#ff3300';
color['mn'] = '#669900';
color['in'] = '#ff9900';
color['asn']= '#cc9900';
color['adn']= '#330099';

function rand(min,max,interval)
{
    if (typeof(interval)==='undefined') interval = 1;
    var r = Math.floor(Math.random()*(max-min+interval)/interval);
    return r*interval+min;
}

function connect_node(map, node1,  node2) {

 return new google.maps.Polyline({
  path: [node1.latLng, node2.latLng],
  geodesic: true,
  strokeColor: color[node1.style],
        strokeOpacity: 0.6,
        strokeWeight: 2,
  map: map
 });
}
 .iot-node-ae, .iot-node-asn, .iot-node-adn, .iot-node-mn, .iot-node-in, .iot-node-info {
 position: absolute;
 list-style-type: none;
 left: 20px;
 top: 20px;
}

.iot-node-ae>a, .iot-node-asn>a, .iot-node-adn>a, .iot-node-mn>a, .iot-node-in>a, .iot-node-info>a {
    position: relative;
    z-index: 2;
    display: block;
    width: 20px;
    height: 20px;
 border-style: solid;
    border-width: 2px;
 border-color: white;
 border-radius: 50%;
    background: #0079ff;
 text-align:center;
 font-weight: bold;
 padding-top:6px;
 padding-left:3px;
 padding-right:3px;
 color:white;
    -webkit-transition: background-color 0.2s;
    -moz-transition: background-color 0.2s;
    -o-transition: background-color 0.2s;
    transition: background-color 0.2s;
}


.iot-node-info>a {
   width: 120px;
   height: 80px;
   position: relative;
   border-radius: 0;
   text-align:left;
}
.iot-node-info>a>span {
position: absolute; top: 2px; right:2px;
    cursor: pointer;
    display:inline-block;
    padding:2px 5px;
    background:#ccc;
}
.iot-node-info>a>span::hover {
position: absolute; top: 2px; right:2px;
cursor: pointer;
  
    display:inline-block;
    padding:2px 5px;
    background:#ccc;
}

.iot-node-info>a::before {
   content:"";
   position: absolute;
   top: 100%;
   left: 0;
   width: 0;
   height: 0;
   border-left: 13px solid transparent;
   border-right: 26px solid #0079ff;
   border-bottom: 13px solid transparent;
}

.iot-node-ae::after, .iot-node-asn::after , .iot-node-adn::after , .iot-node-mn::after , .iot-node-in::after , .iot-node-info::after{
 content: '';
 position: absolute;
 border-radius: 50%;
 width: 100%;
 height: 100%;
 top: 0;
 left: 0;
 //animation: cd-pulse 2s infinite;

}

 
@keyframes cd-pulse
{
 0%  {box-shadow:0 0 0 0 #0079ff}
 100%{box-shadow:0 0 0 20px rgba(255,150,44,0)}
}
/* AE */
.iot-node-ae{
 
}
.iot-node-ae>a{
  background: #ff3300;
  font-size:14px;
}

.iot-node-ae::after{
 //animation: cd-pulse 2s infinite;
}

/* asn */
.iot-node-asn{
 
}
.iot-node-asn>a{
  background:  #cc9900;
}

.iot-node-asn::after{
 //animation: cd-pulse 2s infinite;
}

/* adn */
.iot-node-adn{
 
}
.iot-node-adn>a{
  background:  #330099;
}

.iot-node-adn::after{
 //animation: cd-pulse 2s infinite;
}

/* mn */
.iot-node-mn{
 
}
.iot-node-mn>a{
  background: #669900;
}

.iot-node-mn::after{
 //animation: cd-pulse 2s infinite;
}

/* IN */
.iot-node-in{
 
}
.iot-node-in>a{
  background: #ff9900;
  font-size:14px;
}


.iot-node-in::after{
 //animation: cd-pulse 2s infinite;
}
<!DOCTYPE HTML>
<html>
<head>

<title>Google Maps API</title>

<style type="text/css">
#map {
 width: 1500px;
 height: 1000px;
}
</style>
<link rel="stylesheet" type="text/css" href="iot_resource.css" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script type="text/javascript" src="iot_resource.js"></script>
<script type="text/javascript" src="init_map.js"></script>
</head>
<body>
 <div id="map">
 </div>
 <button onclick="Draw1()" />
</body>
</html>