Reputation: 29463
I have a Google Maps API initialization function, where the Marker label color (for an array of markerPins) is set to transparent
:
markerPins[i] = new google.maps.Marker({
position: position,
map: map,
optimized: false,
icon: myPin,
label: {
color: 'transparent', // <= HERE
fontSize: '11px',
fontWeight: '900',
text: 'Example Label'
}
});
This works. So far, so good.
At a later point (following a user action etc.) I would like to change the Marker label color.
I have written the following function:
// CHANGE MARKER LABEL COLOR
function changeMarkerLabelColor(labelColor) {
for (let i = 0; i < markerPins.length; i++ ) {
markerPins[i].label.color = labelColor;
}
}
And it does work. But seemingly only as the map is being initialised.
How is it possible to get
and set
the Marker label color after the map has initialized?
I am happy to deploy a javascript approach, a CSS approach, or any other approach - but I've been searching and testing and experimenting for hours and so far come up empty-handed.
Upvotes: 2
Views: 4318
Reputation: 161334
There is no documented label
property of a marker. Use the (documented) .setLabel
and .getLabel
functions:
function changeMarkerLabelColor(labelColor) {
for (let i = 0; i < markerPins.length; i++ ) {
var label = markerPins[i].getLabel();
label.color = labelColor;
markerPins[i].setLabel(label);
}
}
code snippet:
var locations = [
{ position: {lat: 37.4419, lng: -122.1419}},
{ position: {lat: 37.4529598, lng: -122.1817252}},
{ position: {lat: 37.4688273, lng: -122.141075}},
];
var markerPins = [];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i = 0; i < locations.length; i++) {
markerPins[i] = new google.maps.Marker({
position: locations[i].position,
map: map,
optimized: false,
label: {
color: 'transparent', // <= HERE
fontSize: '11px',
fontWeight: '900',
text: 'Example Label'
}
});
}
setTimeout(function() {
changeMarkerLabelColor("blue");
}, 5000)
}
google.maps.event.addDomListener(window, "load", initialize);
function changeMarkerLabelColor(labelColor) {
for (let i = 0; i < markerPins.length; i++) {
var label = markerPins[i].getLabel();
label.color = labelColor;
markerPins[i].setLabel(label);
}
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
Upvotes: 7