1

how i can draw a polygon on google map with user input coordinates. I have two input fields (lat and lng) and when the user clicks the button I want to draw the polygon. I have this code but it does not work. Can anyone help me?

HTML:

<form onsubmit="show(this.lat.value, this.lon.value); return false;">
    <p><label>Latituda</label></p>
       <input type="text" size="13" id="latbox2" name="lat" value="">
    <p><label>Longituda</label></p>
       <input type="text" size="13" id="lonbox2" name="lon" value="">                        
    <p><input type="submit" id="button2" value="Show" class="btnsearch" ></p>
</form>

JavaScript:

function xz() {
    if (GBrowserIsCompatible()){
            map = new GMap2(document.getElementById("map_canvas"));
            map.setCenter(new GLatLng(43.500752, 16.435547), 6);
            map.setUIToDefault();
            map.addMapType(G_SATELLITE_3D_MAP);
            map.enableGoogleBar();
    }
  }
    function show(lat, lon){
        var latOffset = 0.01;
        var lonOffset = 0.01;
        var polygon = new GPolygon([
            new GLatLng(lat, lon - lonOffset),
            new GLatLng(lat + latOffset, lon),
            new GLatLng(lat, lon + lonOffset),
            new GLatLng(lat - latOffset, lon),
            new GLatLng(lat, lon - lonOffset)
        ], "#f33f00", 5, 1, "#ff0000", 0.2);
        map.addOverlay(polygon);
    }
Kara
  • 6,115
  • 16
  • 50
  • 57
Josip
  • 67
  • 1
  • 6
  • What is function `xz()`? Why is `show()` defined within that? It's almost never a good idea to nest functions: always define them as global unless you know *exactly* why you are nesting them. – Andrew Leach May 25 '12 at 06:21
  • Sorry, I forgot put } to close function xz(). Function show() is not defined within that. I updated the code now. Function xz() is used to load the google map. – Josip May 25 '12 at 10:08

1 Answers1

1

You don't actually say what's wrong with this, but having experimented it does appear that GLatLng() requires Numbers and not Strings. The documentation does say to use Numbers; the content of an input field is a String.

Converting them to Numbers seems to work (although zoom 6 means the polygon is very small). Note that I've also added a setCenter() at the end so it's visible.

var lat = parseFloat(lat);
var lon = parseFloat(lon);

http://jsfiddle.net/csRCd/1/

Andrew Leach
  • 12,945
  • 1
  • 40
  • 47