Script Code :
<script type="text/javascript">
$(function () {
$("[id*=btnSave]").bind("click", function () {
var location = {};
location.Locationname = $("[id*=locationname]").val();
location.Description = $("[id*=description]").val();
GetLocation($("#txtAddress").val());
$.ajax({
type: "POST",
url: "Location.aspx/SaveLocation",
data: JSON.stringify(location) ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("added successfully.");
}
});
return false;
});
});
function GetLocation(address) {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("txtAddress").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
location.latitude = results[0].geometry.location.lat();
location.longitude = results[0].geometry.location.lng();
var mapOptions = {
center: new google.maps.LatLng(location.latitude, location.longitude),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
} else {
alert("Location not found.");
}
});
};
</script>
HTML Code :
<table class="form">
<tr>
<td style="text-align:left">
<label>Location Name</label>
<asp:TextBox ID="locationname" runat="server" Text="" />
<label>Description</label>
<asp:TextBox ID="description" runat="server" Text="" />
<input type="button" id="btnSave" value="Save Location" class="btn" />
</td>
<td style="text-align:right">
<label>Search</label>
<input type="text" id="txtAddress" value="Rajkot"/>
<input type="button" onclick="GetLocation()" value="Get Location" class="btn"/>
</td>
</tr>
</table>
C# Code :
public partial class Location : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string SaveLocation(Locations location,string latitude, string longitude)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Locationlatlng VALUES(@Locationname,@Latitude, @Longitude, @Description)"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Locationname", location.Locationname);
cmd.Parameters.AddWithValue("@Latitude", latitude);
cmd.Parameters.AddWithValue("@Longitude", longitude);
cmd.Parameters.AddWithValue("@Description", location.Description);
cmd.Connection = con;
con.Open();
cmd.ExecuteScalar();
con.Close();
return "Latitude: " + latitude + " Longitude: " + longitude;
}
}
}
}
public class Locations
{
public string Locationname { get; set; }
public string Description { get; set; }
}