Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  36] [ 7]  / answers: 1 / hits: 109472  / 12 Years ago, fri, june 15, 2012, 12:00:00

I am new to JS and the Google API and I am trying to make multiple markers each with a label.



From little snippets I've been looking at, there was no simple way to attach a label to a marker in Google Maps API v3. Between Google and stackoverflow searches, everyone used a roundabout procedure that involved creating or editing the label class.



I just want to figure out how to attach a label to each marker in a simple way since I am just starting to learn JS/ Google API v3.



Thanks



EDIT #3:
Okay I finally figured out what was wrong and correctly implemented multiple markers with labels using Lilina's code. Apparently we both defined the var map differently and that itself makes both our codes unable to synchronize well.



I have an additional question now that I am able to use labels for each marker.
I want to be able to hide markers and their labels based on the zoom level that the user is at.



Google Maps API v3 - Different markers/labels on different zoom levels


More From » html

 Answers
25

I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.



 .labels {
color: red;
background-color: white;
font-family: Lucida Grande, Arial, sans-serif;
font-size: 10px;
font-weight: bold;
text-align: center;
width: 60px;
border: 2px solid black;
white-space: nowrap;
}


JavaScript:



 var marker = new MarkerWithLabel({
position: homeLatLng,
draggable: true,
map: map,
labelContent: $425K,
labelAnchor: new google.maps.Point(22, 0),
labelClass: labels, // the CSS class for the label
labelStyle: {opacity: 0.75}
});


The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50).



In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|


[#84887] Thursday, June 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevenjeffreyr

Total Points: 286
Total Questions: 112
Total Answers: 95

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;