How To Listen To Property Change Of An Object?
I'm new to google maps api and js in general. I have a project with 2 circle objects and they can change radius and center coordinates, every time one of those properties change I
Solution 1:
The Google Maps Javascript API v3 is event based. A google.maps.Circle has events that fire when any of its properties changes. Add an event listener to your circles to listen for the radius_changed event.
cityCircle = new google.maps.Circle(populationOptions);
google.maps.event.addListener(cityCircle, 'radius_changed', radiusChanged);
working code snippet based on the 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;
functionradiusChanged() {
document.getElementById('info').innerHTML = "<b>" + this.title + "</b><br>radius=" + this.radius.toFixed(2) + " km";
};
functioninitialize() {
// 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
}
<scriptsrc="https://maps.googleapis.com/maps/api/js"></script><divid="info"></div><divid="map-canvas"style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
Post a Comment for "How To Listen To Property Change Of An Object?"