Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
368 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...