Adding custom marker text to Google Map

2019-02-16 06:16发布

问题:

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:

<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>

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

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

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

<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>

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

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?

回答1:

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"));


回答2:

Yo can set the Latitude and Longitude of your marker and include a Title on it.

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


回答3:

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>