Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MarkerWithLabel label center alignment

I'm using the MarkerWithLabel extension in Google Maps API v3. I would like to set the label below the picture to be center aligned. There is an LabelAnchor property that sets the position of the label, and I also use an CSS labelClass like this:

var myMarker = new MarkerWithLabel(
{
    position: latlng,
    draggable: false,
    raiseOnDrag: false,
    map: map,
    labelContent: "my text",
    labelAnchor: new google.maps.Point(25, 0), //(25, 27),
    labelClass: "my_label", // the CSS class for the label
    labelStyle: {opacity: 0.8},
    icon: image,
    labelInBackground: true,
    labelVisible: true,
    clickable: true,
    zIndex: 11
});

.my_label 
{
    color: black;
    background-color: beige;
    font-family: "Lucida Grande", "Arial", sans-serif;
    font-size: 10px;
    text-align: center;
    width: auto;     
    white-space: nowrap;
    padding: 4px;
    border: 1px solid grey;
    border-radius:3px;   
    box-shadow: 2px 2px 20px #888888;
}

Is it possible to auto align the label box, or do I need to calculate the text width and set the LabelAnchor manually? And if so, how do I calculate the text width?

like image 323
Magnus Avatar asked Feb 24 '13 09:02

Magnus


1 Answers

The other solutions will work, but they either require a fixed width, a hook into an event, or need you to wrap your content in a parent container and add a bunch of styling. Since the label is a DOM element that can take CSS styling, the easiest way to center the label is to simply use transform: translateX(-50%) in the CSS:

JS:

new MarkerWithLabel({
  labelAnchor: { x: 0, y: 30 },
  labelClass: 'marker-label'
})

CSS:

.marker-label {
  transform: translateX(-50%)
}

You may have to bump the labelAnchor X a pixel or two to make it look visually centered.

like image 107
Daniel T. Avatar answered Oct 17 '22 09:10

Daniel T.