Reputation: 559
I have on my web application a text area that allows the user to enter the vertices of a polygon. i want to implement a button that when clicked, a polygon with entered vertices will be drawn in a google maps. the vertices will always be in the following format:
25.82024674666931, 55.66104912743973,
25.54465656761206, 48.11048789757425,
25.22561664287819, 5.57756899014949,
25.47485219998054, 26.21461743851616
what is the best way to do it.
your help is highly appreciated
Upvotes: 0
Views: 719
Reputation: 6057
It's only a few steps, without complications if you trust the input to always be clean.
First, convert the comma-separated text to an array of LatLngs.
function textToLatLngs(text) {
var dots = text.value.split(",");
var latLngs = [];
for(var i = 0; i < dots.length; i += 2) {
latLngs[i/2] = new google.maps.LatLng(parseFloat(dots[i]),
parseFloat(dots[i+1]));
}
return latLngs;
}
Next, with the LatLngs you can define a polygon:
function drawPolygon(vertices) {
var polygon = new google.maps.Polygon({
strokeColor: "#f33",
fillColor: "#fce",
paths: vertices,
map: map
});
}
Finally, link the HTML and Javascript with an event listener (I put mine in initialize()
)
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(25.0, 25.0),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addDomListener(
document.getElementById("button1"),
'click',
function() {
drawPolygon(textToLatLngs(document.getElementById('coordsinput')));
});
}
With an HTML form like:
<form id="form">
<input id="button1" type="button" value="get polygon">
<br /><br />
<textarea id="coordsinput" cols="22" rows="20">
25.82024674666931, 55.66104912743973,
25.54465656761206, 48.11048789757425,
25.22561664287819, 5.57756899014949,
25.47485219998054, 26.21461743851616
</textarea>
</form>
The button will draw new polygons each time the button is clicked. If you want to just move a single polygon, you need to call setPaths when the button is clicked.
http://jsbin.com/enepis/edit#preview
Upvotes: 1