I'm trying to fill 2 inputs with google autocomplete and then get google map directions asd route.
I manage to use autocomplete, but when I click in the submit button nothing happens.
I'm using this code:
function initialize() {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(39.57182223734374, -7.811279296875), 15);
gdir = new GDirections(map, document.getElementById("directions"));
var input = document.getElementById('tb_fromPoint');
var autocomplete = new google.maps.places.Autocomplete(input);
var input2 = document.getElementById('tb_endPoint');
var autocomplete2 = new google.maps.places.Autocomplete(input2);
setDirections();
}
function setDirections() {
var fromAddress = document.getElementById('tb_fromPoint');
var toAddress = document.getElementById('tb_endPoint');
gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": "pt_PT" });
}
google.maps.event.addDomListener(window, 'load', initialize);
From :
To:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Directions service</title>
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places" type="text/javascript"></script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(13.0524139, 80.25082459999999);
var mapOptions = {
zoom:7,
center: chicago
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('city1').value;
var end = document.getElementById('city2').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width: 650px; height: 350px;"></div>
<script type="text/javascript">
function initialize1() {
var options = {
types: ['(cities)'],
componentRestrictions: {country: "in"}
};
var input1 = document.getElementById('searchTextField1');
var autocomplete = new google.maps.places.Autocomplete(input1,options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place1 = autocomplete.getPlace();
document.getElementById('city1').value = place1.name;
document.getElementById('cityLat1').value = place1.geometry.location.lat();
document.getElementById('cityLng1').value = place1.geometry.location.lng();
document.getElementById('cityy').value = place1.city_name;
initialize();
calcRoute()
});
}
google.maps.event.addDomListener(window, 'load', initialize1);
function initialize2() {
var options = {
//types: ['(cities)'],
componentRestrictions: {country: "in"}
};
var input2 = document.getElementById('searchTextField2');
var autocomplete = new google.maps.places.Autocomplete(input2, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place2 = autocomplete.getPlace();
document.getElementById('city2').value = place2.name;
document.getElementById('cityLat2').value = place2.geometry.location.lat();
document.getElementById('cityLng2').value = place2.geometry.location.lng();
initialize();
calcRoute()
});
}
google.maps.event.addDomListener(window, 'load', initialize2);
</script>
<input id="searchTextField1" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" /> <br />
<input type="text" id="city1" name="city1" /> <br />
<input type="text" id="cityLat1" name="cityLat1" /> <br />
<input type="text" id="cityLng1" name="cityLng1" /> <br />
<input id="searchTextField2" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" /> <br />
<input type="text" id="city2" name="city2" /> <br />
<input type="text" id="cityLat2" name="cityLat2" /> <br />
<input type="text" id="cityLng2" name="cityLng2" /> <br />
</body>
</html>
Related
Problem:
I have a form with some input fields, and i'm trying to convert the adress to geocode before it submits to my controller (using Spring MVC). But somehow my geolocation field is empty after the conversion... And for some reason the same code does work on a form without a submit. Can someone help me please? Thanks a lot!
Code:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="domain.Location"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Leuven Speaks</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
</head>
<body>
<jsp:include page="header.jspf"/>
<script type="text/javascript" src="<c:url value="/js/style.js" />"></script>
<form name="addLocation" method="POST" action="addLocation.htm" commandName="location" onsubmit="changeAdress()">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Adres</td>
<td><input type="text" id="adress" name="adress"/></td>
</tr>
<tr>
<td><input type="text" id="geolocation" name="geolocation"/></td>
</tr>
</table>
<input type="hidden" name="id" value="${location.id}"/>
<input type="submit" name="action" value="Save"/>
<input type="submit" name="action" value="Cancel"/>
</form>
</body>
<script type="text/javascript">
function changeAdress(){
var adres = document.getElementById("adress").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': adres}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
document.addLocation.geolocation.value = latitude + " " + longitude;
}
});
//geolocation is empty...
alert(document.getElementById("geolocation").value);
return true;
}
</script>
</html>
Geocoding is asynchronous, submit the form it the callback routine.
function changeAdress(){
var adres = document.getElementById("adress").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': adres}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
document.addLocation.geolocation.value = latitude + " " + longitude;
alert(document.getElementById("geolocation").value);
document.addLocation.submit();
} else alert("geocode failed:"+status);
});
return false;
}
proof of concept fiddle
Thanks for the previous answer.
I have added a some more drawings to the canvas.I have also times(*) everything by 3 so I can see the lines better.
There is a straight line from the top to the bottom.
Is there a way to figure out where "var hdr" would hit that line?
h1 needs to be calculated for when hdr+h2 hits the line.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var p1=7.5*3;
var p2=10.25*3;
var lp=16
var max = lp; // how many times
ctx.moveTo(0,0);
for(i=1; i <= max; i++){
ctx.lineTo(p2*(i-1),p1 * i);
ctx.lineTo(p2 * i,p1 * i);
}
ctx.lineTo(p2*lp,p1*lp);
ctx.lineTo(0,0);
ctx.stroke();
var htx = c.getContext("2d");
var h1=100*3//h1 needs to be calculated
var h2=12*3
var h3=3*3
var hdr=80*3
htx.rect(h1,0,h3,h2);
htx.stroke();
ctx.lineTo(h1,h2);
ctx.lineTo(h1,hdr);
ctx.stroke();
</script>
</body>
</html>
This code has progressed quite well, how do I scale this so it always fits in the canvas?
<!DOCTYPE html>
<html>
<body>
<label for="text1">LP:
<input type="text" size="5" maxlength="5" name="text1" value="16" id="lp" />
</label>
<label for="text2">p1:
<input type="text" size="5" maxlength="5" name="text2" value="7.50" id="p1" />
</label>
<label for="text3">p2:
<input type="text" size="5" maxlength="5" name="text2" value="10.0" id="p2" />
</label>
<label for="text4">h2:
<input type="text" size="5" maxlength="5" name="text4" value="12" id="h2" />
</label>
<label for="text5">hdr:
<input type="text" size="5" maxlength="5" name="text5" value="80" id="hdr" />
</label>
<input type="button" value="Calculate" onclick="calc()">
<br>
<br>
<br>
<br>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
<br />Your browser does not support the HTML5 canvas tag.</canvas>
<script type="text/javascript">
function calc() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var p1 = parseFloat(document.getElementById("p1").value);
var p2 = parseInt(document.getElementById("p2").value);
var lp = parseInt(document.getElementById("lp").value);
var max = lp; // how many times
ctx.moveTo(0, 0);
for (i = 1; i <= max; i++) {
ctx.lineTo(p2 * (i - 1), p1 * i);
ctx.lineTo(p2 * i, p1 * i);
}
ctx.lineTo(p2 * lp, p1 * lp);
ctx.lineTo(0, 0);
ctx.stroke();
var htx = c.getContext("2d");
var h2 = parseInt(document.getElementById("h2").value);
var h3 = 3
var hdr = parseInt(document.getElementById("hdr").value);
var h1 = ((h2 + hdr) / p1 * p2) //h1 needs to be calculated
htx.rect(h1, 0, h3, h2);
htx.stroke();
ctx.lineTo(h1, h2);
ctx.lineTo(h1, hdr + h2);
ctx.stroke();
alert(h1)
}
</script>
</body>
</html>
thanks
I replicated the Developer's example code with success. When i insert a div into the form it fails. How can i submit 'form div input' to a server side function?
* i believe divs and spans are allowed inside forms from here.
* uncommenting the divs causes the div 'output' not to update.
html:
<form id="myForm">
<!--><div>-->
<input name="myEmail" type="text" />
<input type="submit" value="Submit"
onclick="google.script.run.withSuccessHandler(updateEmail)
.processForm(this.parentNode)" />
<!--></div>-->
</form>
<div id="output">
</div>
<script>
function updateEmail(response) {
var div = document.getElementById("output");
div.innerHTML = "<p>" + response + "</p>";
}
</script>
code.gs
function doGet() {
var html = HtmlService.createTemplateFromFile('index').evaluate()
.setTitle('Web App').setSandboxMode(HtmlService
.SandboxMode.NATIVE);
return html;
}
function processForm(formObject) {
var response = "";
response = formObject.myEmail;
return response;
};
Edit:
changed:
<input type="button" value="Submit"
to:
<input type="submit" value="Submit"
I changed the HTML file to this:
<form id="myForm">
<div>
<input name="myEmail" type="text" />
<input type="button" value="Submit"
onclick="processFormJs(this.parentNode)" />
</div>
</form>
<div id="output"></div>
<script>
window.processFormJs = function(argDivParent) {
console.log('argDivParent: ' + argDivParent);
google.script.run.withSuccessHandler(updateEmail)
.processForm(argDivParent)
};
function updateEmail(response) {
var div = document.getElementById("output");
div.innerHTML = "<p>" + response + "</p>";
}
</script>
And added a console.log('argDivParent: ' + argDivParent); statement. Then in developer tools, show the console. I get this error:
argDivParent: [domado object HTMLDivElement DIV]
Failed due to illegal value in property: 0
this.ParentNode is referring to the DIV and not the FORM. If I take out the DIV, the object returned is:
argDivParent: [domado object HTMLFormElement FORM]
Not:
argDivParent: [domado object HTMLDivElement DIV]
A DIV probably doesn't automatically put INPUT values into it's parent object.
This code does work with a DIV:
<form id="myForm" onsubmit="processFormJs(this)">
<div>
<input name="myEmail" type="text" />
<input type="button" value="Submit"/>
</div>
</form>
<div id="output"></div>
<script>
window.processFormJs = function(argDivParent) {
console.log('argDivParent: ' + argDivParent);
google.script.run.withSuccessHandler(updateEmail)
.processForm(argDivParent)
};
function updateEmail(response) {
var div = document.getElementById("output");
div.innerHTML = "<p>" + response + "</p>";
}
</script>
For debugging, you can use Logger.log("your text here"); then view the Logs.
function processForm(formObject) {
Logger.log('processForm ran: ' + formObject);
var response = "";
response = formObject.myEmail;
Logger.log('response: ' + response);
return response;
};
I am trying to add multiple forms which associates different types of document but when I try to add a file from second form it shows up in primary form submission and also for process event. Please advise what could be wrong here.
<form accept-charset="UTF-8" action="/docs/1" class="documents" enctype="multipart/form-data" id="new_document" method="post">
<div class="input-append" >
<input class="filestyle" did="pdoc" id="document_doc_file" name="document[doc_file]" type="file" uid="template-upload-1" />
</div>
<input id="document_doc_type" name="document[doc_type]" type="hidden" value="1" />
</form><script id="template-upload-1" type="text/x-tmpl">
<div class="upload">
{%=o.name%}<span class="pull-right" id="pbar">Uploading 0%</span></span>
<div class="progress"><div class="bar" style="width: 0%"></div></div>
</div>
</script>
<div id="pdoc"></div>
<form accept-charset="UTF-8" action="/docs/1" class="documents" enctype="multipart/form-data" id="new_document" method="post">
<div class="input-append" >
<input class="filestyle" did="ldoc" id="document_doc_file" name="document[doc_file]" type="file" uid="template-upload-2" />
</div>
<input id="document_doc_type" name="document[doc_type]" type="hidden" value="2" />
</form><script id="template-upload-2" type="text/x-tmpl">
<div class="upload">
{%=o.name%}<span class="pull-right" id="pbar">Uploading 0%</span></span>
<div class="progress"><div class="bar" style="width: 0%"></div></div>
</div>
</script>
<div id="ldoc"></div>
<script type="text/javascript">
$(function () {
$('.documents').fileupload({
dropZone: $(this).find('input:file'),
dataType: 'script',
fileInput: $(this).find('input:file'),
singleFileUploads: true,
add: function(e, data) {
var file, types;
types = /(\.|\/)(pdf|xls|xlsx)$/i;
file = data.files[0];
if (types.test(file.type) || types.test(file.name)) {
uid = $(this).find(':file').attr('uid');
if ($('#' +uid).length > 0) {
data.context = $(tmpl(uid, file).trim());
}
did = $(this).find(':file').attr('did');
$('#' + did).append(data.context);
data.submit();
} else {
alert("" + file.name + " is not a pdf or an excel file.");
}
},
progress: function (e, data) {
if (data.context) {
var progress = parseInt(data.loaded / data.total * 100, 10);
data.context.find('.bar').css('width', progress + '%');
if (progress < 100) {
data.context.find('#pbar').html('Uploading ' + progress + '% ...');
} else {
data.context.find('#pbar').html('Upload Complete');
}
}
}
});
$(document).bind('drop dragover', function (e) {
e.preventDefault();
});
});
</script>
The variable 'this' that you use is ambiguous and might be the cause for the problem.
The simplest solution would be to initiate each form separately - in a for loop over the results of $('.documents') or if you are expecting only two forms just give each of them an id doc1 and doc2 and build the fileupload for each.
I'm running the simple Echo example of WebSockets but it doesn't seem to establish a connection. This is happening on Windows 7, Eclipse, and Tomcat.
The error messages in firefox are:
"NetworkError: 404 Not Found - http://my_ip_address:8080/websockets/echo"
and
Firefox can't establish a connection to the server at ws://my_ip_address:8080/websockets/echo.
What am I missing? Is there some configuration I need to set up?
The jars I have in the build path are javax.annotation_1.0.jar and websocket-api-0.2.jar
The code I'm running:
package org.javaee.glassfishwebsocket;
import org.glassfish.websocket.api.annotations.WebSocket;
import org.glassfish.websocket.api.annotations.WebSocketMessage;
#WebSocket(path="/echo")
public class EchoBean {
#WebSocketMessage
public String echo(String message) {
System.out.println("##################### Message received");
return message + " (from your server)";
}
}
This is index.jsp:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<meta charset="utf-8">
<title>WebSocket Echo Client</title>
<script language="javascript" type="text/javascript">
console.log("trying to connect");
var wsUri = "ws://my_ip_address:8080/websockets/echo";
console.log("wsUri = ");
console.log(wsUri);
var websocket = new WebSocket(wsUri);
console.log("websocket = " );
console.log(websocket);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
function init() {
console.log("init called");
output = document.getElementById("output");
}
function send_echo() {
console.log("sending_echo with " + textID.value);
websocket.send(textID.value);
writeToScreen("SENT: " + textID.value);
}
function onOpen(evt) {
console.log("onOpen");
writeToScreen("CONNECTED");
}
function onMessage(evt) {
console.log("onMessage");
writeToScreen("RECEIVED: " + evt.data);
}
function onError(evt) {
console.log("onError");
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<h2 style="text-align: center;">WebSocket Echo Client</h2>
<div style="text-align: center;"><img style=" width: 64px; height: 64px;" alt=""src="HTML5_Logo_512.png"></div>
<br></br>
<div style="text-align: center;">
<form action="">
<input onclick="send_echo()" value="Press me" type="button">
<input id="textID" name="message" value="Hello WebSocket!" type="text"><br>
</form>
</div>
<div id="output"></div>
</body>
</html>