如何在标记上应用自定义CSS样式而不应用图像或图标

时间:2019-10-02 06:17:54

标签: google-maps-api-3 google-maps-markers

我想显示标记内容和标记标签的自定义样式。 谷歌搜索之后。所有示例都在讨论如何设置setIcon并提供我不需要的图像URL。

是否可以自定义如下标签样式?

谢谢

    <Marker
        key={loc.estimate_address}
        position={{
            lat: loc.lat,
            lng: loc.lng
        }}

        // I can only put STRING here! I thought we could put html snippet <label> XXXX </label>
        label={this.getMarkerLabel(loc)}


        onClick={e => this.onMarkerClick(null, loc, e)}
    >

预期

enter image description here

当前版本

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为您可以使用SVG并在其上编写文本,并利用setIcon方法来实现预期的输出,如下所示:

function initialize() {

    var myLatLng = new google.maps.LatLng(44.4375, 12.3358),
        myOptions = {
            zoom: 5,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        },
        map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
        marker = new google.maps.Marker({
            position: myLatLng,
            map: map
        });

    marker.setMap(map);
    marker.setIcon(getIcon('Test'));
}

function getIcon(message) {
    var svg = '<svg width="140" height="120" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"><g><path stroke="#000000" fill="#FF0000" stroke-width="5" d="m8,11.26568l123.54244,-3.20295l0.45756,54.45019l-41.63838,1.83026l-54.45019,38.89299l23.33579,-41.18081l-49.87454,3.20295l-1.37269,-53.99262z" id="svg_2"/><text fill="#000000" stroke-width="0" x="152.85671" y="81.24476" id="svg_3" font-size="24" font-family="serif" text-anchor="middle" xml:space="preserve" transform="matrix(1.4942564059587096,0,0,1.018637442728764,-156.2965919229571,-38.08934344654804) " stroke="#000000">' + message + '</text></g></svg>'; 

    return {
            url: 'data:image/svg+xml;base64,' + window.btoa(svg),
            scaledSize: new google.maps.Size(60, 60),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(20,40)
        };
}

initialize();
#map-canvas {
    height: 400px;
    width: 600px;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>

jsfiddle