Here is my group's project: https://github.com/stuycs-ml7-projects/YAN-SHAN-PHAN-WU
We're working on app (a website) that can store messages at locations using GPS. Messages can only be accessed and stored at their specific coordinates.
I'll go through what I have.
HTML initializes the variables
<input type="hidden" id="Latitude" name="Latitude">
<input type="hidden" id="Longitude" name="Longitude">
I use a document.ready function to call getLocation() which stores them in the hidden fields.
function getLocation()
{if (navigator.geolocation)
{ navigator.geolocation.watchPosition(showPosition); }
}
function showPosition(position)
{
document.getElementById("Latitude") = position.coords.latitude;
document.getElementById("Longitude") = position.coords.longitude;
}
$(document).ready(function() {
getLocation();
});
If I press a button, it will request the data in app.py
Latitude = request.form['Latitude']
Longitude = request.form['Longitude']
Then find all the messages at the location
messages = database.returnMessagesinRange(Latitude,Longitude)
return render_template('SCAN.html',messages=messages,
Latitude = Latitude, Longitude = Longitude)
Somewhere along the line, I lose the coordinates and end up with blank variables. Any ideas how to fix, or possibly a shortcut to avoid all the trouble?
That's a quick guess, but try replacing document.getElementById("Latitude") = ... with document.getElementById("Latitude").value = ...
Related
I have a Google Form to collect information from my workers working in remote locations
Emp No *
Punch *
Customer details / mode or travel
The data goes into a Google spreadsheet with the below structure
Timestamp Emp No Punch Remark Name GeoCode GeoAddress Email
I am able to capture the GPS co-ordinates of the user by the below script. I made a web app (anyone even anonymous can run) and asked the user to click the link.
What I am not able to do :
I want to save the email ID (or emp no) of the user filling the form. But the email ID is not getting captured into the form. If I fill the form, the email ID is captured. For other users it is not captured. I don't want all the users to authenticate the script (to run the script as the logged in user). It must be captured by some other way. Is it possible?
If the GPS is not captured (it is empty), I want to display a different message in the HTML page. How to do it?
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile("Index");
}
//
function getLoc(value) {
var destId = FormApp.getActiveForm().getDestinationId() ;
var ss = SpreadsheetApp.openById(destId) ;
var respSheet = ss.getSheetByName("Location");
var numResponses = respSheet.getLastRow();
var currentemail = Session.getActiveUser().getEmail();
var c=value[0]; var d=value[1];
var e=c + "," + d ;
//respSheet.getRange(numResponses,6).setValue(e);
//respSheet.getRange(numResponses,8).setValue(currentemail);
var response = Maps.newGeocoder().reverseGeocode(value[0], value[1]);
var f= response.results[0].formatted_address;
//respSheet.getRange(numResponses,7).setValue(f);
respSheet.getRange(numResponses,6,1,3 ).setValues([[ e, f, currentemail ]]);
}
//
index.html
<!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>
<body>
<p>Please ensure your GPS is on to record your location. You can generate the report from website to check. Pl. close this window (version 3)</p>
</body>
</html>
From the question
I want to save the email ID (or emp no) of the user filling the form. But the email ID is not getting captured into the form. If I fill the form, the email ID is captured. For other users it is not captured. I don't want all the users to authenticate the script (to run the script as the logged in user). It must be captured by some other way. Is it possible?
On a web application created using Google Apps Script to automatically get the user email ID you could set your web application to be executed as the user running the application instead being executed as you but if don't want to use this feature then you have to set your own authentication process.
From the question
If the GPS is not captured (it is empty), I want to display a different message in the HTML page. How to do it?
Use a JavaScript conditional expression
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert('Can\'t get the position');
}
})()
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);
}
}
The above code uses alert but you could use the DOM.
Resources
Web Apps | Google Apps Script
Document Object Model (DOM)
I was able to make a complete solution without any google form (just HTML) and managed to display an alert message also. The "Login" is still not possible.
Code.gs
It runs the form and saves the answers in the required columns into google sheet.
It runs faster than google form and "Submit" has to be clicked only once.
As the saving happens by "append row", the jumbling of data (between rows) which was happening in my earlier method is avoided.
/* #Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
/* #Process Form */
function processForm(formObject) {
var url = "https://docs.google.com/spreadsheets/d/...../edit#gid=52499297";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Location");
var response = Maps.newGeocoder().reverseGeocode(formObject.lat, formObject.long);
var address= response.results[0].formatted_address;
ws.appendRow(
[
new Date(),
formObject.empno,
formObject.punch,
formObject.rem,
"",
formObject.lat+","+formObject.long,
address
]
);
}
Index.html
This has the questions.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<?!= include('JavaScript'); ?>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-6">
<form id="myForm" onsubmit="handleFormSubmit(this);">
<p class="h4 mb-4 text-left">Record Attendance and Location</p>
<div class="form-group">
<label for="empno">Emp No - Click to see list</label>
<input type="number" class="form-control" id="empno" name="empno" min="1" max="9999999" required>
</div>
<div class="form-group">
<label for="punch">Punch (Select one)</label>
<select class="form-control" id="punch" name="punch" required>
<option selected disabled hidden style='display: none' value=''></option>
<option value="In">In</option>
<option value="Out">Out</option>
<option value="Started">Started</option>
<option value="Reached">Reached</option>
</select>
</div>
<div class="form-group">
<label for="rem">Remark</label>
<input type="text" class="form-control" id="rem" name="rem">
</div>
<div class="form-group">
<input type="hidden" class="form-control" id="lat" name="lat">
<input type="hidden" class="form-control" id="long" name="long">
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div id="output"></div>
</div>
</div>
</div>
</body>
</html>
JavaScript.html
This processes the answers
<script>
function showPosition() {
navigator.geolocation.getCurrentPosition(showMap);
}
function showMap(position) {
// Get location data
var lat = position.coords.latitude;
var geo1 = document.getElementById("lat");
geo1.value = lat;
var long = position.coords.longitude;
var geo2 = document.getElementById("long");
geo2.value = long;
}
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
window.addEventListener('load', showPosition);
function handleFormSubmit(formObject) {
google.script.run.processForm(formObject);
document.getElementById("myForm").reset();
alert('Data saved successfully');
}
</script>
I want to call a page to get geolocation, then auto submit form to my php page to $_REQUEST getlat and getlon without clicking a submit button. Here is what I have. In my browser inspector I see my geolocation values, but it will not auto submit. I tried using the onload function in my body tag, but then found you can only call one function at a time, also I read this is a bad practice anyway. I have view another similar questions but cant piece it together. Thanks for any help
<html>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
showPosition,
positionError
);
}
}
function showPosition(position) {
document.getElementById('getlat').value = position.coords.latitude;
document.getElementById('getlon').value = position.coords.longitude;
lon = document.getElementById('getlon').value;
lat = document.getElementById('getlat').value;
}
function positionError(error) {
if (error.PERMISSION_DENIED) alert('Please accept geolocation');
hideLoadingDiv();
showError(
'Geolocation is not enabled. Please enable to use this feature'
);
}
</script>
<script>
function PageLoad() {
getLocation();
document.frm1.submit();
}
</script>
<body>
<script>
window.onload = PageLoad();
</script>
<form action="results.php" name="frm1">
<input type="hidden" name="longitude" id="getlon" />
<input type="hidden" name="latitude" id="getlat" />
</form>
</body>
</html>
You must be unaware of the asynchronous nature of javascript otherwise it's a very simple problem. Anyway here I explain
When page loads and it finds window.onload=PageLoad(); it calls the PageLoad() function and then
function PageLoad() {
getLocation(); // <-- gets called
document.frm1.submit(); // <-- doesn't wait for getLocation() to complete;
// rather runs right away
}
As you can guess, while getLocation() is doing it's job (in sorta "thread" A) document.frm1.submit(); gets run (in another sorta "thread" B) and submits the form which isn't what you expect.
So what you need to do instead is move the submit related code in the showPosition() so once browser gets the location and then form is submitted.
function showPosition(position) {
document.getElementById("getlat").value = position.coords.latitude;
document.getElementById("getlon").value = position.coords.longitude;
lon=document.getElementById("getlon").value;
lat=document.getElementById("getlat").value;
document.frm1.submit(); <-- submits when browser gets the users location
}
According mdn documentation
getCurrentPosition() method. This initiates an asynchronous request to
detect the user's position
You are sending the form before obtaining the coordinates. The solution is to send this form with the value of the updated hidden inputs just when the asynchronous request ends. Please try the following example
Having this html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<form action="results.php" name="frm1">
<input type="hidden" name="longitude" id="getlon" />
<input type="hidden" name="latitude" id="getlat" />
</form>
<script src="geo.js"></script>
</body>
</html>
JS
document.addEventListener('DOMContentLoaded', () => {
pageLoad();
});
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, positionError);
}
}
function showPosition(position) {
console.log(position);
document.getElementById('getlat').value = position.coords.latitude;
document.getElementById('getlon').value = position.coords.longitude;
lon = document.getElementById('getlon').value;
lat = document.getElementById('getlat').value;
document.frm1.submit(); // here the form is submit
}
function positionError(error) {
if (error.PERMISSION_DENIED) alert('Please accept geolocation');
hideLoadingDiv();
showError('Geolocation is not enabled. Please enable to use this feature');
}
function pageLoad() {
getLocation();
}
Here I ma using when DOM is ready
I'm just starting to learn JavaScript and therefore do not know much about how Forms are used or how to read from them. I'm trying to play around with Google's Geocode, and need some help with building a JS Form to read from.
I have the following JS code, outputting the longitude & latitude, and simply need a form to store some addresses in. The code I have looks as follows:
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value;
geocoder.geocode( {'address': address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK)
{
results[0].geometry.location.latitude
results[0].geometry.location.longitude
}
else
{
alert("Geocode was not successful for the following reason: " + status)
}
});
I'd like some help if possible to build a form this code can read an address from, where the ElementID = "address". How would such a form look? I'd much appreciate if someone could take a minute or two and explain how the JS works with the form. Any help is appreciated! Thank you, guys.
JS dosent care what the element is you just need to get the reference of the form from the DOM then you can do what you want (get the value).
a simple form can look like this
<form>
First name:<br>
<input type="text" id="firstname"><br>
Address:<br>
<input type="text" id="address">
</form>
<button onclick="myFunc()">Done!</button>
So when the button is click it will run a function myFunc which will get your data from the form and alert it.
function myFunc(){
var name = document.getElementById("firstname").value;
var address = document.getElementById("address").value;
alert(name + " lives at " + address);
}
more on getting elements by id here
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
you can also use jquery
function myFunc(){
var name = $("#firstname").val();
var address = $("#address").val();
alert(name + " lives at " + address);
}
https://api.jquery.com/id-selector/
First create a Form in html. Include your external javascript file in it.
<head>
<script type="text/javascript" src="index.js"></script> //index.js is name of javascript file which is in same location of this jsp page.
</head>
<body>
<form name="EmployeeDetails" action="ServletEmployee" method="post">
Employee Name:<input type="text" id="name"><br>
EmployeeID:<input type="text" id="employID"><br>
<input type="submit" value="Submit">
</form>
<input type="button" name="Click" id="mybutton" onclick="myButtonClick">
</body>
In your external javascript file...that is index.js
window.onload = function(){ // function which reads the value from html form on load without any button click.
var employeename = document.getElementById("name").value;
var employeeid = document.getElementById("employID").value;
alert("Name : "+employeename+" : EmployeeID : "+employeeid);
}
function myButtonClick(){ // function to read value from html form on click of button.
var empname = document.getElementById("name").value;
var empid = document.getElementById("employID").value;
alert("Name : "+empname+" : EmployeeID : "+empid);
}
Im trying to get my current location but the problem is the address which the marker points is only the nearest street where I am now. How can I get my place accurately?
Heres the screen shot. Thanks in advance :)
Click here
<input type="button" value="Show Location" onclick="showlocation()"/>
<br/>
Latitude: <span id="latitude">..</span> <br>
Longitude: <span id="longitude">..</span><br>
Address: <span id="add">..</span><br>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function showlocation(){
navigator.geolocation.watchPosition(callback);
}
function callback(position){
document.getElementById('latitude').innerHTML=position.coords.latitude;
document.getElementById('longitude').innerHTML=position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var latLng = new google.maps.LatLng(latitude,longitude);
geocoder.geocode({
latLng: latLng
},
function(responses)
{
if (responses && responses.length > 0)
{
address(responses[0].formatted_address);
}
else
{
alert('Not getting Any address for given latitude and longitude.');
}
}
);
}
function address(str)
{
document.getElementById('add').innerHTML = str;
}
</script>
Use Geolocation API. To obtain your current location, you can call the getCurrentPosition() method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information.
When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.
This documentation and example might help you.
I want to get latitude and longitude of a city by providing the API with the city name. It should work for most cities regardless how the user inputs the city.
For example:
City can be 'miami, US' or city can be 'miami, united states'
How do I print its latitude?
You can find the code jsfiddled here : http://jsfiddle.net/YphZw/
or below :
$("#btn").click(function(){
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': 'miami, us'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
} else {
alert("Something got wrong " + status);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body>
<input id="btn" type="button" value="search for miami coordinates" />
</body>
</html>
If you want more examples for the Javascript API, try this link : https://developers.google.com/maps/documentation/javascript/examples/
The code I wrote is inspired from the geocoding-simple sample.
Regards.
EDIT 1:
You can achieve it using an non-official PHP library. Check this example :
http://www.bradwedell.com/phpgooglemapapi/demos/geocoding.php
(The code is at the bottom=
You can use Google's geocoding service, e.g.,
http://maps.googleapis.com/maps/api/geocode/xml?address=Miami+FL&sensor=false
That gives you back georeferenced data in a variety of formats (JSON, XML, etc). In any event, the location is definitely in the returned data block.
The API docs are at:
https://developers.google.com/maps/documentation/geocoding/
Update per comment below: Doesn't work after July 2018.
This seems needlessly complicated. Here's an example "nearby events" map. It will take City, States, convert them to latLng coords, and put markers on a map:
// Nearby Events with Google Maps
window.nearbyEventsMap = () => {
const centerOfUS = {
lat: 37.09024,
lng: -95.712891
}
// Create a map object and specify the DOM element for display.
const map = new google.maps.Map(document.querySelector('#nearby_events_map'), {
center: centerOfUS,
scrollwheel: false,
zoom: 4
})
// Create a marker and set its position.
const geocoder = new google.maps.Geocoder()
// Filter out duplicate cityStates
let cityStates = {}
document.querySelectorAll('.nearby_event_city_state').forEach(event => {
cityStates[event] = event.innerText
})
// `cityState` is in the format of "City, State". It's not picky about state being a word or the abbreviation.
for (const cityState in cityStates) {
const location = cityStates[cityState]
geocoder.geocode({
address: location
}, function (results, status) {
if (status === 'OK') {
const result = results[0].geometry.location
const lat = result.lat()
const lng = result.lng()
const latLng = {
lat,
lng
}
return new google.maps.Marker({
map: map,
position: latLng
})
}
})
}
}
// /Nearby Events with Google Maps
Make sure to include your <script> tags.
<script src="/dist/js/main.js"></script>
<!-- We're loading this after the main.js script so the callback from main.js will be available to it. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=nearbyEventsMap"></script>
StackOverflow please join everyone else and get GitHub markdown with syntax highlighting...