Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API v3 marker with label

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

like image 879
krikara Avatar asked Jun 15 '12 01:06

krikara


People also ask

Can you Label points on Google Maps?

Or drop a pin by tapping and holding a place on the map. At the bottom, tap the name of the place. Tap Label.


1 Answers

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

like image 155
Tina CG Hoehr Avatar answered Oct 05 '22 04:10

Tina CG Hoehr