Reputation: 217
I'm using this function to draw the marker:
function pinSymbol(color) {
return {
path: 'M31.5,0C14.1,0,0,14,0,31.2C0,53.1,31.5,80,31.5,80S63,52.3,63,31.2C63,14,48.9,0,31.5,0z M31.5,52.3 c-11.8,0-21.4-9.5-21.4-21.2c0-11.7,9.6-21.2,21.4-21.2s21.4,9.5,21.4,21.2C52.9,42.8,43.3,52.3,31.5,52.3z',
fillColor: color,
fillOpacity: 1,
strokeColor: '#000',
strokeWeight: 0,
scale: 1,
};
}
and this is my marker:
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: pinSymbol("#fff"), //defined marker color
labelText: 'HERE WE ARE',
labelVisible: true,
labelClass: "label",
labelZIndex: 99,
draggable: false,
map: map
});
I have a color pallete in other file with the jQuery script that changes a lot of colors on the page when user choose some color, but I don't know how to change color of this marker also.
Can I somehow change color of the marker externaly, in some other file?
Upvotes: 1
Views: 2044
Reputation: 14701
When you create a variable using var keyword in javascript that is a local variable. If you want to reach that variable from another javascript file, you need to pass this reference around or use a global variable. With global variable approach, easiest to understand but in the long run hardest to maintain, you may do something like following:
CreateMap.js
<script type="text/javascript">
function pinSymbol(color) {
return {
path: 'M31.5,0C14.1,0,0,14,0,31.2C0,53.1,31.5,80,31.5,80S63,52.3,63,31.2C63,14,48.9,0,31.5,0z M31.5,52.3 c-11.8,0-21.4-9.5-21.4-21.2c0-11.7,9.6-21.2,21.4-21.2s21.4,9.5,21.4,21.2C52.9,42.8,43.3,52.3,31.5,52.3z',
fillColor: color,
fillOpacity: 1,
strokeColor: '#000',
strokeWeight: 0,
scale: 1,
};
}
function initialize() {
var mapOptions = {
center: { lat: -34.397, lng: 150.644},
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: pinSymbol("#fff"), //defined marker color
labelText: 'HERE WE ARE',
labelVisible: true,
labelClass: "label",
labelZIndex: 99,
draggable: false,
map: map
});
// global variables set
window.currentMap = map;
window.mainMarker = marker;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
AnotherMapScript.js
<script type="text/javascript">
var marker = window.mainMarker;
marker.setIcon(pinSymbol('#f20'));
</script>
Upvotes: 2
Reputation: 55613
You can't do it without having a reference to your marker. As soon as you have that reference, it's easy:
marker.setIcon(pinSymbol('#f00'));
https://developers.google.com/maps/documentation/javascript/reference#Marker
Upvotes: 0