How to import an Excel file in to a database using angularJS1, hibernate(4.3.5), Spring(4.2.4)? - angularjs-1.5

I want to import an Excel file into my database using angularJS1, Hibernate 4.3.5, Spring mvc 4.2.4. The Excel file is imported via a window (table consisting of children "last name, first name", and parents), the table was filled before manually. The goal now is to fill the table automatically by importing an Excel file. I can read the Excel file on google (json format), but I can not import it into my database. The project consists of a front part (angularJS1) and a back part (hibernate, postgresSQL, DAO). Could you help me please ? This is since Thursday that I seek a solution. Thank you
Here is the code to read my excel file in json format : file : ... Controller.js (front part)
$scope.uploadFile = function (element) {
var file = element.files[0];
console.log("FILE", file);
var reader = new FileReader();
reader.onload = function (event) {
var data = event.target.result;
/*Call XLSX*/
var workbook = XLSX.read(data, {
type: 'binary'
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
var excelData = XLSX.utils.sheet_to_json(worksheet);
console.log("EXCELDATA", excelData);
}
}

Here is a sample codepen example created for you.
angular.module('app', [])
.controller('ExcelReadCtrl', function($scope) {
$scope.data = [{firstName:'AAA',lastName:'BBB',age:30}];
$scope.READ = function() {
/*Checks whether the file is a valid excel file*/
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xlsx|.xls)$/;
var xlsxflag = false; /*Flag for checking whether excel is .xls format or .xlsx format*/
if ($("#ngexcelfile").val().toLowerCase().indexOf(".xlsx") > 0) {
xlsxflag = true;
}
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
if (xlsxflag) {
var workbook = XLSX.read(data, { type: 'binary' });
}
else {
var workbook = XLS.read(data, { type: 'binary' });
}
var sheet_name_list = workbook.SheetNames;
var cnt = 0;
sheet_name_list.forEach(function (y) { /*Iterate through all sheets*/
if (xlsxflag) {
var exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
}
else {
var exceljson = XLS.utils.sheet_to_row_object_array(workbook.Sheets[y]);
}
if (exceljson.length > 0) {
for (var i = 0; i < exceljson.length; i++) {
$scope.data.push(exceljson[i]);
$scope.$apply();
}
}
});
}
if (xlsxflag) {
reader.readAsArrayBuffer($("#ngexcelfile")[0].files[0]);
}
else {
reader.readAsBinaryString($("#ngexcelfile")[0].files[0]);
}
};
});
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.7.7/xlsx.core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.core.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
crossorigin="anonymous"></script>
</head>
<body>
<div ng-app>
<h2>Excel Format should be same as table below, xls.core.min.js reads first row as headers</h2>
<div ng-controller="ExcelReadCtrl">
<form>
<input type="file" id="ngexcelfile" />
<input type="button" value="Read Data" ng-click="READ()" />
<br />
<br />
<table border=1>
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in data">
<td>{{item.lastName}}</td>
<td>{{item.firstName}}</td>
<td>{{item.age}}</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</body>
</html>
your excel format must be same as data you are trying to load.
Here is example format.
Once you load Excel data is stored in $scope.data use same to pass to backend

Instead of trying to read Excel on Front-End side just upload your excel to the server. Excel Reading via JS will consume a significant amount of MEM in browser.
On Java side its quite easy to read/Write Excel all you need is Apache POI
For Excel reading ref : https://www.mkyong.com/java/apache-poi-reading-and-writing-excel-file-in-java/
Once you done with excel reading, you can pass required data to hibernate to store in DB.

I have to read the excel file on the front because it is the user who update the data in the table by importing the Excel file through a upload interface.

Related

How do I accept file uploads from pasting a file into the browser?

Accepting image uploads from a paste into the browser window is much easier than traditional file upload form inputs and even the newer style drag 'n' drop file uploads.
How do I implement it?
Here's an example PHP/JavaScript page that accepts drag 'n' drop image uploads. It's not dependent on PHP though - you could adapt it quite easily to work with another server-based language. This code was based on a snippet I found on jsFiddle by someone called Nick.
This is a full page - so you should be able to copy the code below and put it in a file on your web-server as-is (if you're not running PHP then you'll need to update the PHP code at the top or point the form to your own form handler script).
<?php
if (!empty($_POST)) {
// Handle the POSTed data here - the image is actually base64 encoded data in
// the $_POST['myTextarea'] variable which you can run through the base64_decode()
// function and then write to a file
$pos = strpos($_POST['myTextarea'], 'base64,');
$encoded = substr($_POST['myTextarea'], $pos + 7);
$raw = base64_decode($encoded);
// Show the base64 encoded $data - use the $raw variable when writing to a file
var_dump($_POST);
exit;
}
?>
<!DOCTYPE html >
<html>
<body>
<h1>File upload using paste</h1>
<p>
You can paste an image, which is on your clipboard, into this window and it will appear below.
If you use Windows you can press <b>PrtScr</b> to get a screenshot on your clipboard. Then
press <b>CTRL+V</b> to paste it into this document.
</p>
<!-- PUT THE ADDRESS OF YOUR FORM HANDLER SCRIPT IN THE ACTION ATTRIBUTE -->
<form action="" method="post">
<div id="form-elements-container">
<input type="text" value="An example text input..." name="myTextInput"><br />
<input type="submit" value="Submit form"><br />
</div>
</form>
<!-- THIS IS WHERE THE IMAGE THUMBNAILS WILL APPEAR -->
<div id="images-container"></div>
<script>
counter = 0;
document.body.onpaste = function (e)
{
// use event.originalEvent.clipboard for newer chrome versions
var items = (e.clipboardData || e.originalEvent.clipboardData).items;
// Find pasted image among pasted items
var blob = null;
for (var i=0; i<items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
// Load image if there is a pasted image
if (blob !== null) {
var reader = new FileReader();
reader.onload = function(e)
{
// Create a new image object from the pasted data
var img = new Image();
img.src = e.target.result;
img.width = 128;
img.height = 128;
img.style.margin = '5px';
// Append the file to the document
document.getElementById('images-container').appendChild(img);
// Add a new textarea to the form
var textarea = document.createElement('textarea');
textarea.name = 'myTextarea_' + counter++;
textarea.value = img.src;
textarea.style.width = '200px';
textarea.style.height = '200px';
document.getElementById('form-elements-container').appendChild(textarea);
};
reader.readAsDataURL(blob);
}
}
</script>
</body>
</html>

Convert Excel form window to Google Sheets window

As you've probably found, there appears to be no equivalent way to add the following Excel form and associated VBA code to Google Sheets or Scripts or Forms:
Is there some add-in that can be used to pop up this image and its controls? This has to be used many times in an accounting sheet to categorize expenditures at tax time.
It may not look exactly the same but I was able to construct a custom dialog in a short period of time to show how HTML service can be used to produce similar results.
First I construct an HTML template that contains the 2 combo boxes with multiple lines.
HTML_Test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('CSS_Test'); ?>
</head>
<body>
<div id="left">
<label for="expenseCategory">Expense Category</label><br>
<select id="expenseCategory" size="10">
</select>
</div>
<div id="middle">
<label for="expenseSubCategory">Expense Sub Category</label><br>
<select id="expenseSubCategory" size="10">
</select>
</div>
<?!= include('JS_Test'); ?>
</body>
</html>
Then a CSS file to contain all my element formatting.
CSS_Test.html
<style>
#expenseCategory {
width: 90%;
}
#expenseSubCategory {
width: 90%;
}
#left {
width: 25%;
float: left;
}
#middle {
width: 50%;
float: left;
}
</style>
And a javascript file for client side javascript. I've simply hard coded some data to show how the select elements are filled in but this could just as easily be done using template scripting, or google.script.run
<script>
var expenses = [["A","1","2","3"],
["B","4","5"],
["C","6","7","8","9","10"]
];
function expenseCategoryOnClick() {
try {
let expenseCategory = document.getElementById('expenseSubCategory');
expenseCategory.options.length = 0;
expenses[this.selectedIndex].forEach( (expense,index) => {
if( index > 0 ) {
let option = document.createElement("option");
let text = document.createTextNode(expense);
option.appendChild(text);
expenseCategory.appendChild(option);
}
}
);
}
catch(err) {
alert("Error in expenseCategoryOnClick: "+err)
}
}
(function () {
// load first expense
let expenseCategory = document.getElementById('expenseCategory');
expenseCategory.addEventListener("click",expenseCategoryOnClick);
expenses.forEach( expense => {
let option = document.createElement("option");
let text = document.createTextNode(expense[0]);
option.appendChild(text);
expenseCategory.appendChild(option);
}
);
expenseCategory = document.getElementById('expenseSubCategory');
expenses[0].forEach( (expense,index) => {
if( index > 0 ) {
let option = document.createElement("option");
let text = document.createTextNode(expense);
option.appendChild(text);
expenseCategory.appendChild(option);
}
}
);
}
)();
</script>
Then there is the server side code bound to a spreadsheet.
Code.gs
function onOpen(e) {
var menu = SpreadsheetApp.getUi().createMenu("Test");
menu.addItem("Show Test","showTest");
menu.addToUi();
}
// include(filename) required to include html files in the template
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function showTest() {
var html = HtmlService.createTemplateFromFile("HTML_Test");
html = html.evaluate();
html.setWidth(800);
SpreadsheetApp.getUi().showModalDialog(html,"Test");
}
The dialog looks like this. Many more html elements can be added as needed. This just shows the basics. This may be more difficult than an wysiwig html editor but I find I have better control of the appearance and function of my pages this way. Notice I clicked "C" and the sub category is filled in automatically.

How do I rename files uploaded to an apps script web app form?

I've made a little web app form by splicing together some code I found. It works nearly perfectly for me, allowing me to upload files to a Google Drive folder, logging the data submitted in the form in a spreadsheet and emailing me when a file is uploaded.
However, what I really want to be able to do is to rename the files that are uploaded according to the form data. For example, if the inputted manufacturer value = "Sony" and the date value = 12-04-2016, then make the filename "Sony_12-04-2016.pdf"
From looking it up as best I can it seems I need to pass the submitted values into the createFile() function but I'm quite new to coding and not really sure what I'm doing here..
Here's what I have so far:
.gs
var TO_ADDRESS = "my email address";
function doGet(e) {
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setTitle('Price List Upload Form')
}
function processForm(theForm) {
var fileBlob = theForm.fileUpload;
Logger.log("fileBlob Name: " + fileBlob.getName())
Logger.log("fileBlob type: " + fileBlob.getContentType())
Logger.log('fileBlob: ' + fileBlob);
var fldrSssn = DriveApp.getFolderById('my Google Drive folder id');
fldrSssn.createFile(fileBlob);
return true;
}
function formatMailBody(obj) {
var result = "";
for (var key in obj) {
result += "<h4 style='text-transform: capitalize; margin-bottom: 0'>" + key + "</h4><div>" + obj[key] + "</div>";
}
return result;
}
function doPost(e) {
try {
Logger.log(e);
record_data(e);
var mailData = e.parameters;
MailApp.sendEmail({
to: TO_ADDRESS,
subject: "New Price List Uploaded",
htmlBody: formatMailBody(mailData)
});
return ContentService
.createTextOutput(
JSON.stringify({"result":"success",
"data": JSON.stringify(e.parameters) }))
.setMimeType(ContentService.MimeType.JSON);
} catch(error) {
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
}
}
function record_data(e) {
Logger.log(JSON.stringify(e));
try {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName('responses');
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1;
var row = [ new Date() ];
for (var i = 1; i < headers.length; i++) {
if(headers[i].length > 0) {
row.push(e.parameter[headers[i]]);
}
}
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
}
catch(error) {
Logger.log(e);
}
finally {
return;
}
}
.html
<form id="gform" autocomplete="on" method="POST" class="pure-form pure-form-stacked"
action="script url" onsubmit="picUploadJs(this)">
<fieldset class="pure-group">
<input name="fileUpload" type="file" />
</fieldset>
<fieldset class="pure-group">
<label for="manufacturer">Manufacturer: </label>
<input id="manufacturer" name="manufacturer" type="text" placeholder="Manufacturer Name" required/>
</fieldset>
<fieldset class="pure-group">
<label for="issueDate">Date Issued: </label>
<input id="issueDate" name="issueDate" type="date" required />
</fieldset>
<fieldset class="pure-group">
<label for="info">Additional Info: </label>
<input id="info" name="info" type="text" placeholder="Any Additional Information"/>
</fieldset>
<fieldset class="pure-group">
<input id="email" name="email" type="hidden" value="test#gmail.com"/>
</fieldset>
<button class="button-success pure-button button-xlarge">
Upload</button>
<div style="display:none;" id="thankyou_message">
<div id="status" style="display: none">
<h2>Uploading. Please wait...</h2>
</div>
</div>
function picUploadJs(frmData) {
document.getElementById('status').style.display = 'inline';
google.script.run
.withSuccessHandler(updateOutput)
.processForm(frmData)
};
function updateOutput() {
var outputDiv = document.getElementById('status');
outputDiv.innerHTML = "<h2>File successfully uploaded!</h2><button class=\"pure-button\">Upload another</button>";
}
The original code comes from here
and here
I probably don't have all the lingo correct, but you have to turn the form submission fields into variables to be able to use them in your .gs script. Once you turn them into variables, you can "build" a filename to your liking, and use it when writing the fileBlob to a file. Given your code above, you should be able to just modify the processForm function as follows:
function processForm(theForm) {
var fileBlob = theForm.fileUpload;
var manufacturer = theForm.manufacturer;
var issueDate = theForm.issueDate;
var myNewFilename = manufacturer + '_' + issueDate + '.pdf';
fileBlob.setName(myNewFilename); //set Name of the blob
var fldrSssn = DriveApp.getFolderById('my Google Drive folder id');
fldrSssn.createFile(fileBlob); // create a file with the blob, name of the file will be the same as set by setName method
return true;
}
Let me also note something that may be helpful for future visitors--how to write a timestamp into the filename. Set a new variable using the Utilities.formatDate function, and then you can concatenate this variable into a filename like in the example above. Here's how to set the variable:
var myTS = Utilities.formatDate (new Date(), Session.getScriptTimeZone(), "yyyyMMdd_HHmmss--") ;
Format is completely flexible--just look up the function for details.
You may want to use the rename(newName) method which renames the document.
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.rename("This is the new name");
Also, here's a related threads: https://productforums.google.com/forum/#!topic/docs/AP9zMPOyjfg and Copy, rename and move a document which might help.

View doesn't update on observablearray.remove(item) in knockout without call to applyBindings

I am learning to use MVC 4/MVVM/Knockout for a web-managed data project. I have been running into a problem updating the View when using the remove function on an observable array. The updates happen when using push or unshift, but not remove. Using the debugger in chrome I can see that the data is being removed from the array, the update event just isn't working.
Snippet from the html is the table below, there is a form I did not include for adding or editing data.
<div id="MessageDiv" data-bind="message: Message"></div>
<div class="tableContainer hiddenHead">
<div class="headerBackground"></div>
<div class="tableContainerInner">
<table id="adapter-table" class="grid" data-bind="sortTable: true">
<thead>
<tr>
<th class="first">
<span class="th-inner">Name</span>
</th>
<th>
<span class="th-inner">DeviceID</span>
</th>
<th>
<span class="th-inner"></span>
</th>
<th>
<span class="th-inner"></span>
</th>
</tr>
</thead>
<tbody data-bind="template: { name: 'AdaptersTemplate', foreach: Adapters }">
</tbody>
</table>
<script id="AdaptersTemplate" type="text/html">
<tr>
<td data-bind="text: Name"></td>
<td data-bind="text: DeviceID"></td>
<td>Edit
<td>Delete
</tr>
</script>
</div>
<input type="button" data-bind='click: addAdapter' value="Add New Adapter" />
<input type="button" data-bind='click: saveAll' value="Save Changes" id="SaveChangesButton" />
</div>
My javascript has been set up to manage the VM as restful and caches the changes. Add, Edit, and Saving/Deleting data all seems to work without throwing errors that I am seeing in the debugger in Chrome. Confirming changes seems to work fine and makes the changes to the database as expected.
$(function () {
var viewModel = new AdaptersModel();
getData(viewModel);
});
function getData(viewModel) {
$.getJSON("/api/AdapterList",
function (data) {
if (data && data.length > 0) {
viewModel.SetAdaptersFromJSON(data);
}
ko.applyBindings(viewModel);
});
}
//#region AdapterVM
function Adapter(name, siFamily, deviceIDs) {
var self = this;
self.Name = ko.observable(name);
self.DeviceID = ko.observable(deviceIDs);
self.ID = 0;
}
function AdaptersModel() {
var self = this;
self.Adapters = ko.observableArray([]);
self.DeleteAdapters = ko.observableArray([]);
self.NewAdapter = ko.observable(new Adapter("", "", "", ""));
self.Message = ko.observable("");
self.SetAdaptersFromJSON = function (jsData) {
self.Adapters = ko.mapping.fromJS(jsData);
};
//#region Edit List Options: confirmChanges
self.confirmChanges = function () {
if (self.NewAdapter().ID == 0) {
self.Adapters.push(self.NewAdapter());
}
};
//#endregion
//#region Adapter List Options: addAdapter, selectItem, deleteItem, saveAll
self.addAdapter = function () {
self.NewAdapter(new Adapter("", "", "", ""));
};
self.selectItem = function (item) {
self.NewAdapter(item);
};
self.deleteItem = function(item) {
self.DeleteAdapters.push(item.ID());
self.Adapters.remove(item);
};
self.saveAll = function () {
if (self.Adapters && self.Adapters().length > 0) {
var filtered = ko.utils.arrayFilter(self.Adapters(),
function(adapter) {
return ((!isEmpty(adapter.Manufacturer())) &&
(!isEmpty(adapter.Name())) &&
(!isEmpty(adapter.DeviceIDs()))
);
}
);
var updateSuccess = true;
if (self.DeleteAdapters().length > 0) {
jsonData = ko.toJSON(self.DeleteAdapters());
$.ajax({
url: "/api/AdapterList",
cache: false,
type: "DELETE",
data: jsonData,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { updateSuccess = true; },
error: function () { updateSuccess = false; }
});
}
var jsonData = ko.toJSON(filtered);
$.ajax({
url: "/api/AdapterList",
type: "POST",
data: jsonData,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
self.SetAdaptersFromJSON(data);
updateSuccess = true && updateSuccess;
},
error: function () { updateSuccess = false; }
});
if (updateSuccess == true) { self.Message("Update Successfull"); }
else { self.Message("Update Failed"); }
}
};
//#endregion
}
//#endregion
ko.bindingHandlers.message = {
update: function(element, valueAccessor) {
$(element).hide();
ko.bindingHandlers.text.update(element, valueAccessor);
$(element).fadeIn();
$(element).fadeOut(4000);
}
};
ko.bindingHandlers.sortTable = {
init: function (element, valueAccessor) {
setTimeout(function () {
$(element).addClass('tablesorter');
$(element).tablesorter({ widgets: ['zebra'] });
}, 0);
}
};
function isEmpty(obj) {
if (typeof obj == 'undefined' || obj === null || obj === '') return true;
if (typeof obj == 'number' && isNaN(obj)) return true;
if (obj instanceof Date && isNaN(Number(obj))) return true;
return false;
}
The specific script portion that is failing to update my html table is:
self.deleteItem = function(item) {
self.DeleteAdapters.push(item.ID());
self.Adapters.remove(item);
};
Everything seems to work except for the remove, so I seem to be at a loss for what to look at next, and I am too new to javascript or knockout to know if this is a clue: If I run ko.applyBindings() command in the self.deleteItem function, I get the update to happen but it does give me an unhandled error:
Uncaught Error: Unable to parse bindings.
Message: ReferenceError: Message is not defined;
Bindings value: message: Message
Message was defined in the VM before binding... was there something I missed in all this?
In the beginning of your Js file you are defining var viewModel = new AdaptersModel(); but lower you are stating that function Adapter() is the view model in your region declaration. It is making your code difficult to read. I am going to take another stab at what you can do to troubleshoot, but I would suggest that your viewmodel contains the adapters and your model contains a class-like instance of what each adapter should be.
The specific error you are getting is because you are binding Message() to something and then deleting Message(). One thing you could do to trouble shoot this is to change your div to something like :
<div id="MessageDiv" data-bind="with: Message">
<h5 data-bind="message: $data"><h5>
</div>
If you could create a fiddle I could give a more definite example of why, but basically if Message() is blank the with binding should not show the header which is undefined after deletion.
What you probably need to do though is look at what is being sent as 'item' and make sure it is not your viewmodel.
self.deleteItem = function(item) {
console.log(item); // << Check console and see what is being returned
self.DeleteAdapters.push(item.ID());
self.Adapters.remove(item);
};
You are probably deleting more than just a single adapter.
This will lead you the right direction, but I would seriously consider either renaming your code.
There was a lot of help solving surrounding issues but nothing actually solved the "why" of the problem. The updates worked perfectly sometimes but not other times. When I was troubleshooting it and started to get it dumbed down and working in JSFiddle I didn't include the data-bind="sortTable: true" in all my working versions. Apparently, if you sort a table or using the code as I did it will not work. The example code I have seen floating around is here at http://jsfiddle.net/gregmason/UChLF/16/, pertinent code:
ko.bindingHandlers.tableSorter = {
init: function (element) {
setTimeout(function () { $(element).tablesorter(); }, 0);
},
update: function (element, valueAccessor) {
ko.utils.unwrapObservable(valueAccessor()); //just to get a dependency
$(element).trigger("update");
}
};
The errant behavior can be obvious by clicking the delete link on the row.
If you click on the row without sorting, you will see the row disappear correctly.
If you first click on a column to re-sort in a different order, THEN delete the row, it remains in the table and appears to have cached.
This can be handled by binding each of the table headers instead of the table itself and replacing the tableSorter code with a custom sort behavior as discussed in this thread:
knockout js - Table sorting using column headers. The sort replacement is here:
ko.bindingHandlers.sort = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var asc = false;
element.style.cursor = 'pointer';
element.onclick = function(){
var value = valueAccessor();
var prop = value.prop;
var data = value.arr;
asc = !asc;
if(asc){
data.sort(function(left, right){
return left[prop]() == right[prop]() ? 0 : left[prop]() < right[prop]() ? -1 : 1;
});
} else {
data.sort(function(left, right){
return left[prop]() == right[prop]() ? 0 : left[prop]() > right[prop]() ? -1 : 1;
});
}
}
}
};
This has fixed my sorting/editing/deleting issues and a working jsFiddle is here: http://jsfiddle.net/gregmason/UChLF/18/

HTML5 Geolocation data loaded in a form to send towards database

i'm busy with a school project and I have to build a web app. One function that I want to use is Google Maps and HTML5 Geo Location to pin point what the location of the mobile user is.
I have found this HTML5 Geo Location function on http://merged.ca/iphone/html5-geolocation and works very well for me. However, I want the adress data to be placed into a form so that I can submit it to my database when a mobile user Geo locates his position. This causes the marker to be saved and can be viewed on a global website.
Who know how to get the "Your address:" data loaded into a input field of a form?
Below you can find my Html file. Maybe somebody got a better suggestion perhaps?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<title>HTML 5 Geolocation</title>
<style>
#map {
height:300px;
width:300px;
}
</style>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1"); google.load("jqueryui", "1");</script>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAiUzO1s6QWHuyzxx-JVN7ABSUL8-Cfeleqd6F6deqY-Cw1iTxhxQkovZkaxsxgKCdn1OCYaq7Ubz3SQ" type="text/javascript"></script>
<script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.8&appid=n2wY9mzV34Hsdslq6TJoeoJDLmAfzeBamSwJX7jBGLnjM7oDX7fU.Oe91KwUbOwqzvc-"></script>
<script type="text/javascript">
// Geolocation with HTML 5 and Google Maps API based on example from maxheapsize: http://maxheapsize.com/2009/04/11/getting-the-browsers-geolocation-with-html-5/
//
// This script is by Merge Database and Design, http://merged.ca/ -- if you use some, all, or any of this code, please offer a return link.
var map;
var mapCenter
var geocoder;
var fakeLatitude;
var fakeLongitude;
function initialize()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition( function (position) {
// Did we get the position correctly?
// alert (position.coords.latitude);
// To see everything available in the position.coords array:
// for (key in position.coords) {alert(key)}
mapServiceProvider(position.coords.latitude,position.coords.longitude);
}, // next function is the error callback
function (error)
{
switch(error.code)
{
case error.TIMEOUT:
alert ('Timeout');
break;
case error.POSITION_UNAVAILABLE:
alert ('Position unavailable');
break;
case error.PERMISSION_DENIED:
alert ('Permission denied');
break;
case error.UNKNOWN_ERROR:
alert ('Unknown error');
break;
}
}
);
}
else
{
alert("I'm sorry, but geolocation services are not supported by your browser or you do not have a GPS device in your computer. I will use a sample location to produce the map instead.");
fakeLatitude = 49.273677;
fakeLongitude = -123.114420;
//alert(fakeLatitude+', '+fakeLongitude);
mapServiceProvider(fakeLatitude,fakeLongitude);
}
}
function mapServiceProvider(latitude,longitude)
{
if (window.location.querystring['serviceProvider']=='Yahoo')
{
mapThisYahoo(latitude,longitude);
}
else
{
mapThisGoogle(latitude,longitude);
}
}
function mapThisYahoo(latitude,longitude)
{
var map = new YMap(document.getElementById('map'));
map.addTypeControl();
map.setMapType(YAHOO_MAP_REG);
map.drawZoomAndCenter(latitude+','+longitude, 3);
// add marker
var currentGeoPoint = new YGeoPoint( latitude, longitude );
map.addMarker(currentGeoPoint);
// Start up a new reverse geocoder for addresses?
// YAHOO Ajax/JS/Rest API does not yet support reverse geocoding (though they do support it via Actionscript... lame)
// So we'll have to use Google for the reverse geocoding anyway, though I've left this part of the script just in case Yahoo! does support it and I'm not aware of it yet
geocoder = new GClientGeocoder();
geocoder.getLocations(latitude+','+longitude, addAddressToMap);
}
function mapThisGoogle(latitude,longitude)
{
var mapCenter = new GLatLng(latitude,longitude);
map = new GMap2(document.getElementById("map"));
map.setCenter(mapCenter, 15);
map.addOverlay(new GMarker(mapCenter));
// Start up a new reverse geocoder for addresses?
geocoder = new GClientGeocoder();
geocoder.getLocations(latitude+','+longitude, addAddressToMap);
}
function addAddressToMap(response)
{
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode that address");
} else {
place = response.Placemark[0];
$('#address').html('Your address: '+place.address);
}
}
window.location.querystring = (function() {
// by Chris O'Brien, prettycode.org
var collection = {};
var querystring = window.location.search;
if (!querystring) {
return { toString: function() { return ""; } };
}
querystring = decodeURI(querystring.substring(1));
var pairs = querystring.split("&");
for (var i = 0; i < pairs.length; i++) {
if (!pairs[i]) {
continue;
}
var seperatorPosition = pairs[i].indexOf("=");
if (seperatorPosition == -1) {
collection[pairs[i]] = "";
}
else {
collection[pairs[i].substring(0, seperatorPosition)]
= pairs[i].substr(seperatorPosition + 1);
}
}
collection.toString = function() {
return "?" + querystring;
};
return collection;
})();
</script>
</head>
<body onLoad="initialize()">
<div id="content">
<div id="map"></div>
<p id="address"></p>
<form id="ContactForm" action="">
<p>
<label>Topic</label>
<input id="event" name="event" maxlength="120" type="text" autocomplete="off"/>
</p>
<p>
<label>Address</label>
<input id="address" name="address" maxlength="120" type="text" autocomplete="off"/>
</p>
<input id="send" type="button" value="Send"/>
<input id="newcontact" name="newcontact" type="hidden" value="1"></input>
</form>
</div>
</body>
</html>
You have to use JavaScript to set the value of address input field, this way
1- Add name attribute to the form and input.
2- document.formName.inputName.value=place.address;
Good Luck