Using ASP.net and WebForms i am trying to store the user's location (Latitude, Longitude) to a database. This presents the problem:
How can i get the user's latitude and longitude into a place where server-side ASP.net code can then save it into a database.
What have you tried?
I don't care which technology is used; i just need their location. My first attempt was to try to use Google Maps in order to access the current location. And while i can use javascript in the browser to get ahold of the current location, i cannot figure out how to transfer that information to the server.
Here's the sample code of my first attempt:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var long = 0;
var lat = 0;
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(18.9300, 72.8200),
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);
google.maps.event.addListener(map, 'click', function (e) {
long = e.latLng.lng();
lat = e.latLng.lat();
alert("Latitude: " + lat + "\r\nLongitude: " + long);
});
}
</script>
<div id="dvMap" style="width: 300px; height: 300px">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</body>
</html>
And below is the .aspx code-behind file. We save the longitude and latitude to the database during the Click event of the button:
protected void Button1_Click(object sender, EventArgs e)
{
//TODO: Ask Stackoverflow how to get these values from browser-land javascript
Double latitude = 0;
Double longitude = 0;
SqlConnection con = new SqlConnection();
con.ConnectionString = "#Data Source=(LocalDB)\v11.0;AttachDbFilename=Database.mdf;Integrated Security=True";
string query1 = "insert into Courses(longi,lati) values (#lati, #longi)";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.Parameters.AddWithValue("#lati", latitude);
cmd1.Parameters.AddWithValue("#longi", longitude);
con.Open();
cmd1.ExecuteNonQuery();
con.Close();
}
Location API
Nothing says i need to be using Google Maps. I know that HTML has a Location API accessible somewhere, somehow. Is there an established way that the browser's Location API can be used to feed the user's location to the server in ASP.net?
Add asp hidden fields, with runat="server" to hold the lat and lng. When you get the lat and lng in your javascript simply populate the hidden fields with those values. Then you can reference the hidden fields values directly in your OnClick handler.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var long = 0;
var lat = 0;
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(18.9300, 72.8200),
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);
google.maps.event.addListener(map, 'click', function (e) {
long = e.latLng.lng();
lat = e.latLng.lat();
document.getElementById("lat").value = lat;
document.getElementById("lng").value = long;
alert("Latitude: " + lat + "\r\nLongitude: " + long);
});
}
</script>
<form id="myForm" runat="server">
<div id="dvMap" style="width: 300px; height: 300px">
</div>
<asp:HiddenField ID="lat" runat="server" />
<asp:HiddenField ID="lng" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
//TODO: Ask Stackoverflow how to get these values from browser-land javascript
Double latitude = Convert.ToDouble(lat.Value);
Double longitude = Convert.ToDouble(lng.Value);
SqlConnection con = new SqlConnection();
con.ConnectionString = "#Data Source=(LocalDB)\v11.0;AttachDbFilename=Database.mdf;Integrated Security=True";
string query1 = "insert into Courses(longi,lati) values (#lati, #longi)";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.Parameters.AddWithValue("#lati", latitude);
cmd1.Parameters.AddWithValue("#longi", longitude);
con.Open();
cmd1.ExecuteNonQuery();
con.Close();
}
Related
I am trying to auto complete a text box with Names from a database. When I go to type in the text box when it is running nothing happens.
I have been following this tutorial but am unable to get it working.
http://www.dotnetodyssey.com/2015/01/14/autocomplete-textbox-using-jquery-asp-net-querying-database-complete-example/
Source code below.
The Aspx page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>
<link href="jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(document).ready(function () {
$("#txtNames").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm1.aspx/GetNames",
data: "{'namePrefix':'" + $("#txtNames").val() + "'}",
dataType: "json",
minLength: 2,
success: function (data) {
response(data.d)
},
error: function (response) {
alert("Error" + res.responseText);
}
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label for="txtNames">Names:</label>
<asp:TextBox ID="txtNames" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
The Code Behind:
[WebMethod]
public static string[] GetNames(string namePrefix)
{
List<string> Name = new List<string>();
DataTable dtNames = new DataTable();
string sqlQuery = "select distinct Name from Houses where Name like '" + namePrefix + "%'";
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, conn);
da.Fill(dtNames);
foreach (DataRow row in dtNames.Rows)
{
string name = Convert.ToString(row["Name"]);
Name.Add(name);
}
}
catch (Exception ex)
{
throw ex;
}
return Name.ToArray<string>();
}
Here is an example of autocomplete textbox:
private void LoadServices()
{
txtServiceName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtServiceName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtServiceName.AutoCompleteCustomSource = colValues;
}
And:
AutoCompleteStringCollection colValues = new AutoCompleteStringCollection();
private void GetAllServices()
{
// get list of Windows services
ServiceController[] services = ServiceController.GetServices();
List<string> ac = new List<string>();
// try to find service name
foreach (ServiceController service in services)
{
ac.Add(service.ServiceName.ToString());
}
colValues.AddRange(ac.ToArray());
}
I have to take Longitude and Latitude Position by textboxes which I have defined in body tag, and that textboxes values should be set in Longitude and Latitude variables which I have defined in javaScript.
This Code does not set textboxes values in Longitude and Latitude variables in JavaScript.
Can anyone help me?
My Code:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC6v5-2uaq_wusHDktM9ILcqIrlPtnZgEk&sensor=false"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
alert("Geo Location is not supported on your current browser!");
}
**latitude** = document.getElementById('latitude').value; //position.coords.latitude;
**longitude** = document.getElementById('longitude').value; //position.coords.longitude;
function success(position) {
**latitude** = document.getElementById('latitude').value; //position.coords.latitude;
**longitude** = document.getElementById('longitude').value; //position.coords.longitude;
var city = position.coords.locality;
var myLatlng = new google.maps.LatLng(latitude, longitude);
var myOptions = {
center: myLatlng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title: "lat: " + latitude + " long: " + longitude
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({ content: "<b>Your Latitude Position: </b>" + latitude + "<br /><b>Your Longitude Position: </b>" + longitude + "" });
infowindow.open(map, marker);
}
function SetValues() {
**latitude** = document.getElementById('latitude').value; //position.coords.latitude;
**longitude** = document.getElementById('longitude').value; //position.coords.longitude;
}
</script>
</head>
<body>
<form id="form1" runat="server">
Latitude Position:
<input type="text" id="latitude" value="" PlaceHolder="Enter Latitude Position"/>
Longitude Position: <input type="text" id="longitude" value="" PlaceHolder="Enter Longitude Position"/>
<input type="submit" value="Set" onclick="SetValues()" />
<div id="map_canvas" style="width: 500px; height: 400px"></div>
</form>
</body>
</html>
Thanks in advance
use an asp Textbox
<asp:TextBox ID="txBox" runat="server" />
and in Javacript use
$get("<%=txBox.ClientID %>").value = x;
to access it.
It may also work without asp Textbox by using
$get("txBoxId").value = x;
I want to add html content into a SQL Server database.
For example, on a label it is shows location coordinates, and after button click it will be added in SQL Server. I have gone so far but every time I click on the button it is added in the database empty, not coordinates.
I will give the source code...
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="tripmeter" runat="server">
<p runat="server">
Starting Location (lat, lon):<br />
<span id="startLat" runat="server"></span>°, <span id="startLon" runat="server"></span>°
</p>
<p runat="server">
Current Location:<br />
<label id="currentLat" runat="server"></label>°, <span id="currentLon" runat="server"></span>°
</p>
<p runat="server">
Distance from starting location:<br />
<span id="distance" runat="server">0</span> km
</p>
<input id="Button1" type="button" value="button" runat="server" onserverclick="MySubmitHandler" />
</div>
<script>
window.onload = function () {
var startPos;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
startPos = position;
document.getElementById("startLat").innerHTML = startPos.coords.latitude;
document.getElementById("startLon").innerHTML = startPos.coords.longitude;
}, function (error) {
alert("Error occurred. Error code: " + error.code);
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from locaton provider)
// 3: timed out
});
navigator.geolocation.watchPosition(function (position) {
document.getElementById("currentLat").innerHTML = position.coords.latitude;
document.getElementById("currentLon").innerHTML = position.coords.longitude;
document.getElementById("distance").innerHTML =
calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
position.coords.latitude, position.coords.longitude);
});
}
};
function calculateDistance(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLat = (lat2 - lat1).toRad();
var dLon = (lon2 - lon1).toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
</script>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void MySubmitHandler(object sender, EventArgs args)
{
try
{
SqlConnection lidhje = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
lidhje.Open();
string fut = "insert into Test (lat) values (#lat)";
SqlCommand komande = new SqlCommand(fut, lidhje);
komande.Parameters.AddWithValue("#lat", currentLat.InnerText);
komande.ExecuteNonQuery();
Response.Write("Success");
lidhje.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
}
Set datatype Text in your database;
eg:
create table temp(
linkId int(10) PRIMARY KEY,
htmlValue Text(200) NULL); // this will store your data in HTML format.
I have routes names in my dropdownlist and arrays with lat/log (polylines) with correspondence by event. How to send this lat/log from code behind to javascript?
<head>
<title></title>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
function GetMap() {
// Initialize the map
var mapOptions = {
credentials: "xxxx",
center: new Microsoft.Maps.Location( 9.74, 2.425),
mapTypeId: Microsoft.Maps.MapTypeId.road,
zoom: 13,
showScalebar: false
}
var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);
var lineVertices = new Array(new Microsoft.Maps.Location(<%#new pts%>));
var line = new Microsoft.Maps.Polyline(lineVertices);
map.entities.push(line);
}
</script>
<style type="text/css">
#form1
{
width: 480px;
}
</style>
<body onload="GetMap();" style="height: 18px; width: 480px">
<form id="form1" runat="server">
<div id='listDiv' style="width:480px; height:30px" >
<asp:DropDownList ID="listPicker" runat="server" Height="25px" Width="218px"
onselectedindexchanged="listPicker_SelectedIndexChanged">
</asp:DropDownList>
</div>
<div id='mapDiv' style="position:absolute; width:480px; height:740px; top: 38px; ">
</div>
</form>
protected void listPicker_SelectedIndexChanged(object sender, EventArgs e)
{
if (listPicker.SelectedIndex == 1)
{
pts = new double[,] {
{ 9.6990549318566, 2.4374476373222},
{ 9.6991218770296, 2.4379291260322},
{ 9.6994116428257, 2.4376508334228},
{ 9.6995069262757, 2.4356545805958},
{ 9.6999728977379, 2.4356384873417},
{ 9.6999845469968, 2.4326612353352},
{ 9.7056459228308, 2.432768526198},
{ 9.7088142924775, 2.4295498753801},
{ 9.7228377868168, 2.4293138409868},
{ 9.7228098349562, 2.4276401425615}};
}else{...}
}
There is a way to send this points to js?
You can try
Dim oGeocodeList As New List(Of [String])()
oGeocodeList.Add(" '37.968002524107035, 23.702445030212402' ")
oGeocodeList.Add(" '37.969, 23.705445030212402' ")
oGeocodeList.Add(" '37.97, 23.709445030212402' ")
Dim geocodevalues = String.Join(",", oGeocodeList.ToArray())
ClientScript.RegisterArrayDeclaration("locationList", geocodevalues)
and in javacrtipt
var locationList;
I am sorry for the vb code.
I am using geomap-linechart api in my application.. I want to view the map and the chart on a drop down selected index changed event.. It doesn't work if i put it inside update panel.. it becomes blank.. but it woks fine if i put the control outside the update panel.. Is there any reason or suggestion for this prob?? is it not possible to use the geomap inside update panel??
this is my code..
<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type='text/javascript' src='http://www.google.com/jsapi'></script>
<script src='http://maps.google.com/maps?file=api&v=2&key=ABCDEFG' type='text/javascript'></script>
<script type='text/javascript'>
google.load('visualization', '1', { 'packages': ['geomap'], 'language': 'fr'});
var countryCode;
// map function
function DrawWorldMap(country, lat, lang, name, count, usercount, user, bandwidth, vtitle, htitle, title1, title2) {
try {
var data = new google.visualization.DataTable();
data.addRows(count);
data.addColumn('string', 'Country');
data.addColumn('number', 'BandWidth');
var contry = country.split(',');
var band = bandwidth.split(',');
for (var i = 0; i < count; i++) {
data.setValue(i, 0, contry[i]);
}
for (var h = 0; h < count; h++) {
data.setValue(h, 1, Number(band[h]));
}
var options = {};
options['dataMode'] = 'regions';
var container = document.getElementById('<%=map_canvas.ClientID%>');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
var lati = lat;
var langi = lang;
var loop = count;
google.visualization.events.addListener(
geomap, 'regionClick', function (e) {
countryCode = e['region'];
CreateCountryMap(lati, langi, name, loop, usercount, country, user, bandwidth, vtitle, htitle, title1, title2);
});
}
catch (exception) {
alert('drawworldmap: ' + exception);
}
drawVisualization(user, bandwidth, usercount, vtitle, htitle, title1, title2); // here am calling the chart function..
}
//chart function
function drawVisualization(User, Bandwidth, counts, vtitle, htitle, title1, title2) {
try {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', title1);
data.addColumn('number', title2);
var username = User.split(',');
var BandWidth = Bandwidth.split(',');
for (var i = 0; i < counts; i++) {
data.addRow([String(username[i]), Number(BandWidth[i])]);
}
// Create and draw the visualization.
new google.visualization.LineChart(document.getElementById('<%=visualization.ClientID%>')).
draw(data, { curveType: "function", pointSize: 5, title: 'User Chart', titlePosition: 'out',
width: 400, height: 350, backgroundColor: 'AliceBlue',
vAxis: { maxValue: 100, title: vtitle }, fontSize: 8, hAxis: { title: htitle }
}
);
}
catch (exception) {
alert(exception);
}
}
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlusername" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddlusername_SelectedIndexChanged" Height="17px"
Width="132px"> </asp:DropDownList>
<div id="visualization" align="center" style="border: thin solid grey;" runat="server"> </div>
<div id='map_canvas' style="border: thin solid grey;" align="center" runat="server"> </div>
<asp:Label ID="lblmap" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
and i'm calling the drawworldmap function from code behind like this..
ScriptManager.RegisterStartupScript(lblmap, this.GetType(), "js2", "google.setOnLoadCallback(DrawWorldMap('" + contry + "','" + city + "','" + langitude + "','" + longitude + "'," + count + "," + usercount + ",'" + username + "','" + bandwidth + "','Bandwidth','UserName','User','BandWidth'));", true);
Pls help if you have any idea..
Thank you..
First solution is call function of load google map again, like initMap() function from javascript.
second solution is make iframe page from map and load it when you click on div of map.
your problem is in update panel it is not loading properly.
so.When you click on div of map again load map by first solution.
other wise use second soluction by loading iframe.
I have done both this thing in my projects.
Hope this will help you.
<script type="text/javascript">
function ActiveTabChanged(sender, e) {
if (sender.get_activeTab().get_headerText().toLowerCase().indexOf('contact') > -1) {
var FrameSrc = ('<%=SetFrameSrc() %>');
document.getElementById('<%=ifrmMap.ClientID %>').src = FrameSrc;
}
}
</script>
<iframe id="ifrmMap" runat="server" height="324px" width="462px" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe>
At Code Behind
/// <summary>
/// Get the iframe source when contact tab active.
/// </summary>
/// <returns></returns>
public string SetFrameSrc()
{
string strSrc = string.Empty;
if (!string.IsNullOrEmpty(queryID))
{
strSrc = //Add Google Map New page url;
}
return strSrc;
}
When you select map from dropdown call this javascript function on selected indexchanged.
put iframe where you put div of map right now. and put map functionality over to new page.
which is loaded in this iframe.and last function is code behind function where you have to set your new page where you
have write map code.