I'm calling the HTML geolocation method to get latitude and longitude and then storing them into 2 separate HiddenFields. These values from the HiddenFields will then be used in the server side (code behind) which will be stored in a table in my database. I searched high and low over stackoverflow to get help for empty values in HiddenFields, saving latitude and longitude into database, client and server side button click, etc.
I'm actually firing this javascript method based on a button, or do you think it's better to be fired window.onload?
I suspect that the functions aren't fired as well.. I have little knowledge on javascript.. Appreciate any help..
Javascript codes and HiddenFields in my WebForm:
<asp:HiddenField runat="server" ClientIDMode="Static" ID="latitudeTB"/>
<asp:HiddenField runat="server" ClientIDMode="Static" ID="longitudeTB"/>
<script type="text/javascript">
function HideLabel() {
var seconds = 3;
setTimeout(function () {
document.getElementById("<%=ErrorPanel.ClientID %>").style.display = "none";
}, seconds * 1000);
};
//GeoLocation Retrieval
var latJS = 0;
var lngJS = 0;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position) {
//position.coords.latitude + "," + position.coords.longitude;
//var lat = document.getElementById("<%=latitudeTB.ClientID %>");
latJS = position.coords.latitude;
lngJS = position.coords.longitude;
document.getElementById("<%= latitudeTB.ClientID %>").value = latJS;
document.getElementById("<%= longitudeTB.ClientID %>").value = lngJS;
alert(document.getElementById("<%= latitudeTB.ClientID %>").value + " " + document.getElementById("<%= longitudeTB.ClientID %>").value);
/*if (lat) {
lat.value = position.coords.latitude;
}*/
//var long = document.getElementById("<%=longitudeTB.ClientID %>");
/*if (long) {
long.value = position.coords.longitude;
}*/
}
function call() {
getLocation();
showPosition(position);
}
</script>
FYI. The button is placed above the HiddenFields and Javascript..
Codes for asp:Button:
<asp:Button ID="BTN_Login" CssClass="btn btn-theme-dark" Text="Login" runat="server" OnClientClick="call();" OnClick="BTN_Login_Click" />
I did actually print out the values of the hiddenfields on server side but i'm getting no values at all..
Debug.WriteLine(latitudeTB.Value);
Debug.WriteLine(longitudeTB.Value);
I hope that the code i added is sufficient..
Setting this on button click event or on window load event boils down to what you what the user experience to be.
Most websites tend to show the geolocation prompt when the DOM is ready.
You need to tweak your getLocation function. getCurrentPosition takes success and error callbacks, both of which are not being passed.
function getLocation(opts) {
return new Promise(function(resolve, reject) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition( resolve,
reject,
opts
);
}
else {
reject(new ReferenceError('Browser does not support geolocation api'));
}
});
}
You can then use it this way:
function setLatLong(latId, longId) {
getLocation()
.then(function(pos) {
var coords = pos.coords;
document.getElementById(latId).value = coords.latitude;
document.getElementById(longId).value = coords.longitude;
})
.catch(function(err) {
// log or fall back to come other Location API?
})
}
function call() {
setLatLong(
"<%= latitudeTB.ClientID %>",
"<%= longitudeTB.ClientID %>");
}
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition
Related
I want to fetch live gps location using javscript to store it in database. I already have implemented it. when user clicks on button. But it fetches location on second click.
Html code
<form action="user_location" method="post" id="form-{{$user->id}}">
#csrf
<input type="hidden" name="id" value="{{$user->id}}">
<input type="hidden" name="location" id="location-{{$user->id}}">
</form>
<a onclick="getLocation({{$user->id}})" class="btn">{{__('Get Location')}}</a>
Javscript code
function getLocation(user_id) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
geolocation = "Geolocation is not supported by this browser.";
}
if(setlocation){
form = document.getElementById("form-"+user_id);
var b = document.getElementById("location-"+user_id)
b.value = x.textContent;
form.submit();
}
}
function showPosition(position) {
x.innerText = position.coords.latitude + "-" + position.coords.longitude;
setlocation = true;
}
The getCurrentPosition function is asynchronous. That means that when it is called, it will allow the code after it to run before finishing. So that means that setLocation will not be true whenever your code reaches the following if statement:
if(setlocation){ // setlocation is still false
Handle your results of getting the position inside the success callback of getCurrentPosition.
function getLocation(user_id) {
if (!navigator.geolocation) {
return;
}
const form = document.getElementById("form-" + user_id);
const location = document.getElementById("location-" + user_id);
navigator.geolocation.getCurrentPosition(function(position) {
const { coords } = position;
location.value = coords.latitude + "-" + coords.longitude;
form.submit();
});
}
I have a Google Form where I want to get the user geolocation along with the inputs.
Currently, I'm able to get it by making the user click on a url after he submits the answers. This is the code in Google Script that does it:
function doGet() {
return HtmlService.createHtmlOutputFromFile("Index");
}
function getLoc(value) {
var destId = FormApp.getActiveForm().getDestinationId() ;
var ss = SpreadsheetApp.openById(destId) ;
var respSheet = ss.getSheets()[0] ;
var data = respSheet.getDataRange().getValues() ;
var headers = data[0] ;
var numColumns = headers.length ;
var numResponses = data.length;
var c=value[0]; var d=value[1];
var e=c + "," + d ;
if (respSheet.getRange(1, numColumns).getValue()=="GeoAddress") {
respSheet.getRange(numResponses,numColumns-2).setValue(Utilities.formatDate(new Date(), "GMT-3", "dd/MM/yyyy HH:mm:ss"));
respSheet.getRange(numResponses,numColumns-1).setValue(e);
var response = Maps.newGeocoder().reverseGeocode(value[0], value[1]);
f= response.results[0].formatted_address;
respSheet.getRange(numResponses,numColumns).setValue(f);
}
else if (respSheet.getRange(1,numColumns).getValue()!="GeoAddress") {
respSheet.getRange(1,numColumns+1).setValue("GeoStamp");
respSheet.getRange(1,numColumns+2).setValue("GeoCode");
respSheet.getRange(1,numColumns+3).setValue("GeoAddress");
}
}
And the Index.html file:
<!DOCTYPE html>
<html>
<script>
(function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
})()
function showPosition(position){
var a= position.coords.latitude;
var b= position.coords.longitude;
var c=[a,b]
getPos(c)
function getPos(value){
google.script.run.getLoc(value);
}
}
</script>
</html>
Instead of making the user click on a url, I want the geolocation to be automatically inputed into the response sheet as the user submits the form. I'm able to make the getLoc function run on a submit trigger, however the html function doesn't run. I believe it might be because the doGet function is already a trigger, but it requires a browser page to be opened in order to run. If that's the case, the ideal solution would be to redirect the browser to the Google Script url after the user submits it, but I can't seem to find a way to do it. Is this the correct approach and how can I make it work?
Thanks in advance!
Maybe this works: https://www.youtube.com/watch?v=J93uww0vMFY
Tutorial on Geotagging (Geo-stamp and Time-stamp) google forms.
Add info on Latitude, Longitude, and Address (Street name and number, city, state, zip code, and country) of a device submitting google forms. Linking user’s location within google forms.
Google forms integration with google maps.
Links to download the scripts are given below:
Code.gs : https://www.youtube.com/redirect?v=J93uww0vMFY&event=video_description&q=https%3A%2F%2Fdrive.google.com%2Fopen%3Fid%3D1D4vTzUGZAf3_ZDVMeW760i1KoZCn37un&redir_token=VQ2rLeQvyQea-mq9_kGhh_Kxihd8MTU5MTgxOTM2OEAxNTkxNzMyOTY4
Index.html : https://www.youtube.com/redirect?v=J93uww0vMFY&event=video_description&q=https%3A%2F%2Fdrive.google.com%2Fopen%3Fid%3D1mYZGYNrXNOxUD8DlDmRdBajy1nc3FKtw&redir_token=VQ2rLeQvyQea-mq9_kGhh_Kxihd8MTU5MTgxOTM2OEAxNTkxNzMyOTY4
My MVC Controller is getting hit twice on page load, and I am stumped on how to solve this problem.
I'm using navigator.geolocation.getCurrentPosition in my Layout page, and that passes the latitude and longitude to my controller.
I have RenderAction in a div, just in case the user has JavaScript disabled, as some people still do
:-(
This is what is causing my problem:
The RenderAction is getting rendered 1st and hitting the controller. Then, the AJAX request is firing and hitting the controller.
So my controller is getting hit twice per request.
Is there something I'm missing which will stop that, because at the moment, all I can think of is to remove the render action from the page.
Code:
<div class="dvWeather">
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
</div>
if (navigator.geolocation) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var aj = "gl";
$.ajax({
url: '#Url.Action("PvCurrentWeatherConditions", "Weather")',
type: 'get',
data: {
lat: lat,
lon: lon,
aj: aj
},
success: function (result) {
$('.dvWeather').html(result);
}
});
}
public PartialViewResult PvCurrentWeatherConditions(string lat, string lon, string aj)
{
if (Request.IsAjaxRequest())
{
try
{
//TODO create Viewmodel
GeoCoordinate gc = new GeoCoordinate();
var latitude = gc.Latitude = Convert.ToDouble(lat);
var longitude = gc.Longitude = Convert.ToDouble(lon);
string latlon = latitude + "," + longitude;
var displayCurrentConditions = _igcc.CurrentConditions(latlon);
return PartialView("pvCurrentWeatherConditions");
}
catch (FormatException)
{
//TODO get ip address
return PartialView("pvLocationBasedOnIpAddress");
}
catch (Exception)
{
return PartialView("pvError");
}
}
return PartialView("pvLocationBasedOnIpAddress");
}
Perhaps use another method for checking if the visitor has javascript disabled, like noscript:
<noscript>
<meta http-equiv="refresh" content="[URL]?java=off">
</noscript>
then handle the querystring in a new action.
You don't have to remove the Render action. Just make another (negative) check in the div:
<div class="dvWeather">
<script type="text/javascript>
//if (!navigator.geolocation) { : Edit
if (navigator.geolocation == null) {
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
}
</script>
</div>
Edit:
if (navigator.geolocation != null) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
This way only one call will be made.
Hope it helps.
I created an HTML button:
...onclick="stLoc();"/>
which gears the stLoc() Javascript function.
My intention is to store the latitude inside the vaulesXarray.
Here's my code:
var valuesX=[];
//This is to show the current position:
function handleLoc(pos) {
var a=pos.coords.latitude;
var b=pos.coords.longitude;
var p = new L.LatLng(+a, +b);
mark(p);
}
//Here I intend to store the latitude using "valuesX.push":
function stLoc(pos) {
var a=pos.coords.latitude;
var b=pos.coords.longitude;
var p = new L.LatLng(+a, +b);
mark(p);
valuesX.push(a);
}
//And this is to enable the geolocation:
function handleErr(pos) {
document.write("could not determine location");
}
if (navigator.geolocation) {
navigator.geolocation.watchPosition(handleLoc,handleErr);
}
else {
document.write("geolocation not supported");
}
The output I get is an empty array.
Your stLoc() function is expecting pos object to be passed as first parameter.
But in your HTML part of example you're not passing this parameter to function:
<a "onclick="stLoc();">
This causes the error and the application flow breaks.
Update:
button
<script type="text/javascript">
var valuesX=[],
lastPos={a: -1, b: -1};
//This is to show the current position:
function handleLoc(pos) {
// in event handler remember lastPos to use it in stLoc on click.
lastPos.a = pos.coords.latitude;
lastPos.b = pos.coords.longitude;
var p = new L.LatLng(lastPos.a, lastPos.b);
mark(p);
}
//Here I intend to store the latitude using "valuesX.push":
function stLoc() {
if(lastPos.a != -1) {
valuesX.push(lastPos.a);
}
return false;
}
//And this is to enable the geolocation:
function handleErr(pos) {
document.write("could not determine location");
}
if(navigator.geolocation) {
navigator.geolocation.watchPosition(handleLoc,handleErr);
}
else {
document.write("geolocation not supported");
}
</script>
For guys looking out for code to implement this functionality in a different way..
Here is the code
<script language="javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script language="javascript">
function geoSuccess(e){
var lat = e.coords.latitude;
var lon = e.coords.longitude;
var myLoc = "Latitude: " + lat + '<br />Longitude: ' + lon;
$("#mylocation").html(myLoc);
}
function geoFailed(e){
$("#mylocation").html("Failed");
}
window.onload=function(e){
if ( navigator.geolocation){
navigator.geolocation.getCurrentPosition(geoSuccess, geoFailed);
} else {
// Error (Could not get location)
$("#mylocation").html("Failed");
}
}
</script>
<div id="mylocation"></div>
I'm trying to retrieve the 2 attributes of seprated function and I debug there values before the end of the function and they have a value but the return value is alwas undifined I don't know why !!
the .js file
function STAAPlanlat(){
alert ("the function");
if (navigator.geolocation) {
//we supposed to call the handlers of the expections
navigator.geolocation.watchPosition(function(position) {
alert("show position ");
// x.innerHTML="Latitude: " + position.coords.latitude +"<br />Longitude: " + position.coords.longitude;
var lat=position.coords.latitude;
var lan=position.coords.longitude;
//x.innnerHTML=out
alert(lat+"<"+lan);
return lan;
});
} else {
alert("error");
}
}
I got the alert with the values of the lan and lat
but when I call on separated file it return undefined return value
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="STAAP1.2.js"> </script>
<script type="text/javascript">
function test(){
var out=STAAPlanlat();
document.getElementById("STAAPlanlat").value = "lan is"+out;
//document.writeln("lan is"+out);
}
</script>
</head>
<body>
<p id="STAAPlanlat">Test the division</p>
<button onclick="test()">STAAPlanlat()</button>
<button onClick="alertme()" >Alert</button>
</body>
</html>
Cause you're not returning it from the main function, you're returning it from the embedded anonymous function which isn't doing anything with it. Do this:
function STAAPlanlat(){
var lat;
var lan;
alert ("the function");
if (navigator.geolocation) {
//we supposed to call the handlers of the expections
navigator.geolocation.watchPosition(function(position) {
alert("show position ");
// x.innerHTML="Latitude: " + position.coords.latitude +"<br />Longitude: " + position.coords.longitude;
lat=position.coords.latitude;
lan=position.coords.longitude;
//x.innnerHTML=out
alert(lat+"<"+lan);
});
return lan;
}
else
alert("error");
}
You are returning in the anonymous function and this value is never assigned to anything. You can do what you want with a callback.
// untested code, hope it works
function STAAPlanlat(callback){
alert ("the function");
if (navigator.geolocation) {
navigator.geolocation.watchPosition(function(position) {
var lat=position.coords.latitude;
var lan=position.coords.longitude;
callback(lat, lan);
});
}
else{
alert("error");
}
}
And your test function...
function test(){
var out;
STAAPlanlat(function(lat, lon) { out = lat; });
}
because function STAAPlanlat doesn't return any value. your anonymous function returns lan but it is asynchronous callback.
add this before return lan;:
document.getElementById("STAAPlanlat").value = "lan is" + lan;