Search code examples
javascriptgoogle-maps-api-3

Google maps circle: how to trigger an event when moved and how to obtain the new center


I was able to make a circle object as an overlay on my google map v3. I set its editable property to true. The next thing I wanted to do was get the coordinates of the center if the user moves the circle. For this I would need some kind of method that's triggered in response to the event. I thought I had this all set up in the initialize function as seen below. However, I'm not getting any alert boxes. So I'm assuming this functions in response to the events are not getting triggered.

function initialize() {  
    cityCenterLatLng = new google.maps.LatLng(cLat, cLong);    
    options = {  
        center : cityCenterLatLng,  
        zoom : 15,  
        mapTypeId : google.maps.MapTypeId.ROADMAP,  
        disableDefaultUI : false,  
        mapTypeControl : true,  
        streetViewControl : true,  
        mapTypeControlOptions : {  
            style : google.maps.MapTypeControlStyle.DEFAULT,  
            position : google.maps.ControlPosition.TOP_LEFT  
        }  
    };  
    map = new google.maps.Map(document.getElementById("map_canvas"), options);  
    $("#map_canvas").css("border", "3px solid black");  
    

    infoWindow = new google.maps.InfoWindow({});  
    
    var c = {  
       strokeColor: "#ff0000",  
       strokeOpacity: 0.8,  
       strokeWeight: 3,  
       fillColor: "#b0c4de",  
       fillOpacity: 0.50,  
       map: map,  
       center: cityCenterLatLng,  
       radius: 1000,  
       editable:true  
   };    
    
    circle = new google.maps.Circle(c);  

    google.maps.event.addListener(circle, 'distance_changed', function()   
    {
        alert('Circle moved');  
        //displayInfo(circle);  
    });  

    google.maps.event.addListener(circle, 'position_changed', function()   
    {  
        alert('distance changed');  
        //displayInfo(circle);  
    });  
}

function displayInfo(widget)   
{  
    var info = document.getElementById('info');  
    info.innerHTML = 'Circle Center:' + circle.get('position') + ',Circle distance: ' +
    circle.get('distance');  
}  

Solution

  • Change distance_changed to center_changed for dragged movement, and use radius_changed to detect resizing. Other events are in the docs.

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

    scroll down to 'Events'.

    For the new values, inside the listener functions, write alert(circle.getCenter()); or circle.getRadius()