I have a Google map with drawing manager enabled where a user can draw a polygon and save it to my db. I added an event listener to the drawingManager object for the overlaycomplete event. When the event is fired, the coordinates of the polygon are written to a hidden field. This works great - the only problem being that if the individual vertices are dragged/changed after that point the event isn't fired. I need to either update the field on(any)change or iterate through the polygon vertices when the user hits submit and write them to the hidden field. I can't quite figure out how to get this to work, but you can see what I have so far here: http://jsfiddle.net/5Y4WT/21/
HTML:
<div id="map_canvas" style="width:500px; height:450px;"></div>
<form method="post" accept-charset="utf-8" id="map_form">
<input type="text" name="vertices" value="" id="vertices" />
<input type="button" name="save" value="Save!" id="save" />
</form>
JavaScript:
var map; // Global declaration of the map
var iw = new google.maps.InfoWindow(); // Global declaration of the infowindow
var lat_longs = new Array();
var markers = new Array();
var drawingManager;
function initialize() {
var myLatlng = new google.maps.LatLng(40.9403762, -74.1318096);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [google.maps.drawing.OverlayType.POLYGON]
},
polygonOptions: {
editable: true
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, "overlaycomplete", function(event) {
var newShape = event.overlay;
newShape.type = event.type;
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
$('#vertices').val(event.overlay.getPath().getArray());
});
}
initialize();
$(function(){
$('#save').click(function(){
//iterate polygon vertices?
});
});
Figured it out!!
I added function overlayClickListener:
function overlayClickListener(overlay) {
google.maps.event.addListener(overlay, "mouseup", function(event){
$('#vertices').val(overlay.getPath().getArray());
});
}
and attached it to the overlay on overlaycomplete:
google.maps.event.addListener(drawingManager, "overlaycomplete", function(event){
overlayClickListener(event.overlay);
$('#vertices').val(event.overlay.getPath().getArray());
});
For the solution in action, see here: http://jsfiddle.net/rvsMH/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With