# ASP.NET - How to add polygon to any of city in GMap using c#

Asked By balaji m on 03-Sep-11 02:18 AM
hi frds

how to add polygon to any of city in GMap using c#

Reena Jain replied to balaji m on 03-Sep-11 02:27 AM
Hi,

The EPoly extension adds seven extra methods to the GPolygon and GPolyline Classes.

To use it, copy the http://econym.org.uk/gmap/epoly.js code into your own webspace and load it like:

`    <script src="epoly.js" type="text/javascript"> </script>`
.Contains(latlng) Returns true if the GLatLng is inside the poly and false if the GLatLng is outside.

The method works for closed or open polygons and polylines. If the shape is open, it considers there to be an additional virtual line from the last point to the first.

If the point happens to lie exactly on the boundary of the polygon, then it may return either true or false.

.Area() Returns the approximate area of the poly in square metres.

The method works for closed or open polygons and polylines. If the shape is open, it considers there to be an additional virtual line from the last point to the first.

The method doesn't fully account for spherical geometry, so the areas of large regions will be less accurate.

.Distance() Returns the total length of the path in metres

.Bounds() Returns the bounds of the polygon or polyline as a GLatLngBounds Object.

.GetPointAtDistance(metres) Returns the GLatLng of a point at the specified distance along the path.

.GetPointsAtDistance(metres) Returns an array of GLatLngs of points at the specified interval along the path.

By calculating all the points in a single pass, this runs a lot faster than calling GetPointAtDistance() in a loop. If the path is shorter than the specified distance, then it returns null.

You could use this for placing mile markers along a route, like this:

```    var points = poly.GetPointsAtDistance(1609.344);

for (var i=0; i<points.length; i++) {
}

```
[There are 1609.334 metres in a mile.]
.GetIndexAtDistance(metres) Returns the vertex number at or after the specified distance along the path.
.Bearing(v1?,v2?) Returns the bearing between vertex v1 and vertex v2. Both parameters are optional.

If you omit v1, then the bearing from the first to last vertex is calculated.
If you specify v1 but omit v2, then the bearing from v1 to the next vertext is calculated.
If either vertex is out of range, it returns void.
If the vertexes are the same point (e.g. a closed path) then it returns zero.

The returned values are in degrees, rounded to one decimal place (because that's about the accuracy of the method used).

http://econym.org.uk/gmap/epoly.htm

Radhika roy replied to balaji m on 03-Sep-11 02:51 AM

Ever wanted to add a Google Map to your site but only had 15 minutes to spare? Now you can add a map and still have time to brag to your mates and bask in the worship that (inevitably) comes afterward.

Basically, the guys over at http://subgurim.net/ have already done all the hard work in writing the .Net wrapper for Google Maps. Problem is, the examples on their site are mostly in spanish & its a bit difficult to find out exactly what is needed to get everything working.

But all this is cutting into your bragging time - so lets get started!

1. Get a Google Maps API key from here:

3. Unzip it, and put it in your \bin directory

Tools -> Choose Toolbox Items -> Browse -> Select the .dll file -> OK
GMap will now be in the ‘Standard’ area of your Toolbox.

6. Drag the GMap from the toolbox onto the page. A new instance of the GMap will appear on the page, with the name ‘GMap1′

<appSettings>

</appSettings>

protected void Page_Load(object sender, EventArgs e)

{

Subgurim.Controles.GeoCode GeoCode = default(Subgurim.Controles.GeoCode);

sStreetAddress = "100 Russell St. Melbourne. VIC. 3000. Australia";

Subgurim.Controles.GLatLng gLatLng = new Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat, GeoCode.Placemark.coordinates.lng);

GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal);

Subgurim.Controles.GMarker oMarker = new Subgurim.Controles.GMarker(gLatLng);

}

Radhika roy replied to balaji m on 03-Sep-11 02:52 AM
 Follow these steps- Step 1. Get a Google Maps API key In order to use Google Maps on your site, you need to register for a free Google Maps API key from here:http://www.google.com/apis/maps/   Step 2. Download the SubGurim Google Maps wrapper dll This one is the best Google Maps wrapper I have found so far http://en.googlemaps.subgurim.net/descargar.aspx.  It is a commercial product (from \$10), or you can put up with the overlayed text in the free versions. Download the gmaps.dll file and add it to your \bin directory.   Step 3. Set up your aspx page In your aspx page, add a few text boxes to gather the address details.  You can simply use one textbox, or split the address to enable validation for suburbs, countries, etc.  I haven't included any form validation in my example.

Suburb:
Country:

Hi,

## Getting Google Maps API Key

The first important step of getting started with the Google Maps API is obtaining the Google Maps API Key. Don’t worry it is free of charge and you receive the key immediately after filling in a form http://code.google.com/apis/maps/signup.html.

## Creating a Simple Map

Okay, now it’s the right time to open Visual Studio and create a new web site.

```<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=<YOUR_API_KEY>&sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(51.5, -0.1), 10);
map.setUIToDefault();
}
}```

Don’t forget to change <YOUR_API_KEY> to an appropriate value. As you can see we have just one function called initialize() that creates a new instance of the map object. We also pass the object – a div – that will be a map container. Then, we invoke the setCenter() method that receives two arguments –coordinates and a zoom level. The setUIToDefault() method just adds the UI manipulators, if you remove or comment that line, you will receive a bare map without any UI controls.

Also, you need to add some code that will run the initialize() function and the HTML code for the map container.

```<body onload="initialize()" onunload="GUnload()">
<form id="form1" runat="server">
<div id="map" style="width: 500px; height: 500px"></div>
</form>
</body>```

The code is pretty self-explanatory, it just adds the handlers for the onLoad and onUnLoad events of the page and also we put a div that will contain the map, you can adjust its width and height in order to get a bigger or a smaller map.

After compiling this page you should see a map similar to this one:

Finding a place by its address

Well, it was pretty simple, but in real life project you usually have to find a place on the maps by its address. This is also possible with the Google Maps API. All you have to do is to make use of the GClientGeocoder class and its method called getLatLang() that accepts two parameters:

• function – a callback function with one parameter point that posses the coordinates of the found place

So, if we want to find a house where Sherlock Holmes lived we have to write the following code:

```<script type="text/javascript">
var map;
var geocoder;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(51.5, -0.1), 10);
map.setUIToDefault();

geocoder = new GClientGeocoder();

showAddress("221B Baker Street, London, United Kingdom");
}
}
geocoder.getLatLng(
function (point) {
if (!point) {
}
else {
map.setCenter(point, 15);
var marker = new GMarker(point);
}
}
);
}
</script>```

Also, we create a map overlay that will contain the address information, for this purpose we create an instance of the GMarker class and use the openInfoWindow() method.

## User Interaction with Map

Okay, but what if we want to let user enter an address in a form and find its on the map? No problems! Just add the necessary field and write an event-handler.

```<script type="text/javascript">
var map;
var geocoder;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(51.5, -0.1), 10);
map.setUIToDefault();

geocoder = new GClientGeocoder();
}
}

geocoder.getLatLng(
function (point) {
if (!point) {
}
else {
map.setCenter(point, 15);
var marker = new GMarker(point);
}
}
);
}
</script>
<form id="form1" runat="server">
<div>
</div>

<div id="map" style="width: 500px; height: 500px"></div>
</form>
</body>```

## Letting Users to Manually Select a Place on the Map

Well, finding a place by its address is certainly cool, but we can add yet another level of interactivity to our map. Basically, we can let users to use manually choose a place on the map by just dragging a marker.

```<script type="text/javascript">
var map;
var geocoder;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
var center = new GLatLng(51.5, -0.1);
map.setCenter(center, 10);
map.setUIToDefault();

var marker = new GMarker(center, { draggable: true });
marker.openInfoWindow("Drag the marker to a specific position");

map.closeInfoWindow();
});

var hdnLat = document.getElementById("<%=hdnLat.ClientID %>");
var hdnLng = document.getElementById("<%=hdnLng.ClientID %>");

hdnLat.value = this.getLatLng().lat();
hdnLng.value = this.getLatLng().lng();

marker.openInfoWindow("New position has been set");
});
}
}
</script>
<form id="form1" runat="server">
<asp:HiddenField ID="hdnLat" runat="server" />
<asp:HiddenField ID="hdnLng" runat="server" />
<div id="map" style="width: 500px; height: 500px"></div>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
</form>
</body>```

If you look at the HTML code, then you will notice that we have added to hidden field that will contain the coordinates of a chosen place, so the first field is for keeping the latitude and the second one is for keeping the longitude. This time when creating a marker we set its options and one of the option is “draggable: true”, so it lets users to drag the marker over the map. Then, we should add event handlers, the main event is “dragend”. It occurs ever time a user place a marker on a new place. As a result, in its event handler we receive the coordinates of a new position and save them in the hidden fields.

Also, we wrote an event handler for the “dragstart” event, just to close the info window while dragging the marker.

In a real world application there would be some server-side code that would place the received coordinates into a database, but in this particular case, we will just output them:

```protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Write("Latitude: " + hdnLat.Value + " Longitude: " + hdnLng.Value);
}```

## Passing the Coordinates from Server-Side to Google Maps

Now, what if we have the coordinates stores somewhere in the database and want to point to that place on the map? Well, it’s still not difficult. We just have to pass the values from server-side to JavaScript.

```<script type="text/javascript">
var map;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));

var lat = <asp:Literal ID="ltrLat" runat="server" />;
var lng = <asp:Literal ID="ltrLng" runat="server" />;

var center = new GLatLng(lat, lng);

map.setCenter(center, 10);
map.setUIToDefault();

var marker = new GMarker(center);
marker.openInfoWindow("Here");
}
}
</script>```

The easiest way to achieve this is to use the ASP.NET Literal controls that doesn’t generate any tags around their values.

Since, those Literal controls are outside of the form tag, we have to use the FindControl() method to access them in code-behind:

```protected void Page_Load(object sender, EventArgs e)
{
Literal ltrLat = (Literal)FindControl("ltrLat");
Literal ltrLng = (Literal)FindControl("ltrLng");

ltrLat.Text = "51";
ltrLng.Text = "0";
}```

## Conclusion

In this tutorial we have covered the basics of working with the Google Maps API. We have learnt how to add a map on a page, how to use geo coding for finding a place by its address on the map. We have also got to know how we can let users interact with a map by dragging a marker and how to receive the marker coordinates and store them on server-side. Finally, we have learnt how to pass the coordinates stored on server-side to the Google Maps API and point to that place on a map.

Also, in this tutorial version 2 of the API was covered, however the 3rd version is currently in Google Labs.

Jitendra Faye replied to balaji m on 03-Sep-11 04:00 AM

I found this http://dotnet.sys-con.com/read/171162.htm recently which I thought was pretty cool. It describes how to build and use an http://asp.net/ Server Control that makes Google Map integration easy within http://asp.net/ applications: