Search code examples
google-maps-api-3alignmentcenter

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?


Solution

  • Not my solution, but there's a blog post at http://shahjahanrussell.blogspot.com.au/2013/04/make-label-text-in-center-for-google.html that worked for me. Essentially:

    .labels{
        color: #fff;
        font-weight: bold;
        font-size: 14px;
        opacity: 1;
        pointer-events: none;
        text-align: center;
        width: 60px;
        white-space: nowrap;
    }
    

    and

    function initialize() {
            map = new google.maps.Map(document.getElementById("map"), mapOptions);
            var marker = new MarkerWithLabel({
              position: new google.maps.LatLng(0,0),
              draggable: true,
              map: map,
              labelContent: "example",
              labelAnchor: new google.maps.Point(30, 0),
              labelClass: "labels", // the CSS class for the label
              labelStyle: {opacity: 0.75}
            });
    
          }