使用外部jQuery更改Google Map标记颜色

时间:2015-05-11 13:20:22

标签: jquery google-maps google-maps-api-3 google-maps-markers 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,
   };
}

这是我的标记:

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
});

我在jQuery脚本的其他文件中有一个颜色托盘,当用户选择一些颜色时会改变页面上的大量颜色,但我不知道如何更改此标记的颜色。

在某些其他文件中,我可以以某种方式改变标记的外部颜色吗?

2 个答案:

答案 0 :(得分:1)

在javascript中使用var关键字创建变量时,该变量是局部变量。如果要从另一个javascript文件中获取该变量,则需要传递此引用或使用全局变量。 使用全局变量方法,最容易理解,但从长远来看,最难维护,您可以执行以下操作:

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>

答案 1 :(得分:0)

如果没有引用标记,则无法执行此操作。只要你有这个参考,就很容易:

marker.setIcon(pinSymbol('#f00'));

https://developers.google.com/maps/documentation/javascript/reference#Marker