问题
I am attempting to retrieve the latlng coordinates of both a polyline and polygon. After I complete the drawing of either object I would like to store the latlng in a database, but for now I am merely trying to show the latlng in a textarea. I have done this easily enough for markers, rectangles, and circles, but the terminology for polylines and polygons is baffling me. When I complete the drawing i use an addDomListener(drawingManager, 'polygoncomplete', ... for polyons and then iterate through all the polygons i have drawn. For each polygon I then iterate through its array of coords. I have searched this forums database and tried the Bermuda triangle example on the Google documentation page. Bermuda Example I have read over the documentation many times and just cant see what i am missing. Any help is appreciated.
//Save polygons data to text area
var polygons = [];
google.maps.event.addDomListener(drawingManager, 'polygoncomplete', function(polygon) {
polygons.push(polygon);
});
google.maps.event.addDomListener(savebutton, 'click', function() {
document.getElementById("savedatapolygon").value = "";
for (var i = 0; i < polygons.length; i++) {
var polygonBounds = polygons[i].getPath();
var xy;
// Iterate over the polygonBounds vertices.
for (var i = 0; i < polygonBounds.length; i++) {
xy = polygonBounds.getAt(i);
contentString += '<br>' + 'Coordinate: ' + i + '<br>' + xy.lat() +',' + xy.lng();
}
document.getElementById("savedatapolygon").value += "polygon(";
document.getElementById("savedatapolygon").value += contentString;
document.getElementById("savedatapolygon").value += ")";
}
});
回答1:
The Google Maps Polygon class returns a MVCArray. You need to use the forEach
method of the MVCArray to loop through it.
var polygonBounds = polygons[i].getPath();
// Iterate over the polygonBounds vertices.
polygonBounds.forEach(function(xy, i) {
contentString += '<br>' + 'Coordinate: ' + i + '<br>' + xy.lat() +',' + xy.lng();
});
document.getElementById("savedatapolygon").value += "polygon(";
document.getElementById("savedatapolygon").value += contentString;
document.getElementById("savedatapolygon").value += ")";
来源:https://stackoverflow.com/questions/14948337/getpaths-polygons-google-maps-api