如何听取对象的属性变化?

时间:2014-12-13 18:45:54

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

我是谷歌地图api和js的新手 我有一个带有2个圆形物体的项目,它们可以改变半径和中心坐标,每当其中一个属性改变时我想执行一个特定的功能。
圆的半径随控制器按下(setradius方法)而变化,圆圈也可以拖动。当用户拖动圆圈时,我不想每帧都执行该功能(如果属性没有改变,则可以在0.1秒后检查,然后才执行)。 希望我没有太复杂。

TL; DR:每次圆的属性发生变化时如何执行函数?

1 个答案:

答案 0 :(得分:0)

Google Maps Javascript API v3基于事件。 google.maps.Circle具有在其任何属性更改时触发的事件。向您的圈子添加一个事件监听器以侦听radius_changed事件。

    cityCircle = new google.maps.Circle(populationOptions);
    google.maps.event.addListener(cityCircle, 'radius_changed', radiusChanged);

基于example in the documentation的工作代码段:

// This example creates circles on the map, representing
// populations in North America.

// First, create an object containing LatLng and population for each city.
var citymap = {};
citymap['chicago'] = {
  center: new google.maps.LatLng(41.878113, -87.629798),
  population: 2714856
};
citymap['newyork'] = {
  center: new google.maps.LatLng(40.714352, -74.005973),
  population: 8405837
};
citymap['losangeles'] = {
  center: new google.maps.LatLng(34.052234, -118.243684),
  population: 3857799
};
citymap['vancouver'] = {
  center: new google.maps.LatLng(49.25, -123.1),
  population: 603502
};

var cityCircle;

function radiusChanged() {
  document.getElementById('info').innerHTML = "<b>" + this.title + "</b><br>radius=" + this.radius.toFixed(2) + " km";
};

function initialize() {
  // Create the map.
  var mapOptions = {
    zoom: 4,
    center: new google.maps.LatLng(37.09024, -95.712891),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

  // Construct the circle for each value in citymap.
  // Note: We scale the area of the circle based on the population.
  for (var city in citymap) {
    var populationOptions = {
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35,
      editable: true,
      draggable: true,
      title: city,
      map: map,
      center: citymap[city].center,
      radius: Math.sqrt(citymap[city].population) * 100
    };
    // Add the circle for this city to the map.
    cityCircle = new google.maps.Circle(populationOptions);
    google.maps.event.addListener(cityCircle, 'radius_changed', radiusChanged);
  }
}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="info"></div>
<div id="map-canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>