reactjsgoogle-maps-api-3google-maps-markersmarkerreact-google-maps

react-google-maps align MarkerWithLabel horizontally


I want to create a marker with a label above, and later on make it so I can click the marker and it opens up info boxes. I have:

<MarkerWithLabel labelAnchor={{x: 0, y: 25}} icon={marker_icons[post.type]} key={post.id} position={{lat: post.location.lat, lng: post.location.lon}}>
    <div style={{fontSize: 14}}>{post.prefix + " " + post.name}</div>
</MarkerWithLabel>

Currently it looks like the left but I want to align the label to look like the right one, how would I be able to do that?

enter image description here


Solution

  • To align label the following option could be considered:

    The following example displays label on top of marker and label content vertically aligned to center

    const Map = (props) => {
    
        const labelSize = { width: 220};
        const labelPadding = 8;
    
        return (
          <GoogleMap 
            defaultZoom={props.zoom}
            defaultCenter={props.center}
          >
            {props.places.map(place => {
              return (
                <MarkerWithLabel
                  labelStyle={{ textAlign: "center", width:labelSize.width + 'px', backgroundColor: "#7fffd4", fontSize: "14px", padding:  labelPadding + "px"}}
                  labelAnchor={{ x: (labelSize.width/2) + labelPadding , y: 80 }}
                  key={place.id}
                  position={{ lat: place.lat, lng: place.lng }}>
                  <span>{place.name}</span>
                </MarkerWithLabel>
              );
            })}
          </GoogleMap>
        );
    }
    

    Demo