I managed to get an autocomplete function to a form input with Maptiler API (OSMNames) (since I find Google Maps API even more confusing).
So here comes the actual problem, I would like to get the driving distance between two places I entered with the help of the autocomplete functions in the two inputs I have created.
I am trying to do so with the OSRM (Open Source Routing Machine) API
Here are my current scripts:
<!--AUTOCOMPLETE-->
<script>
var autocomplete = new kt.OsmNamesAutocomplete(
'search1', 'https://geocoder.tilehosting.com/', '#My_Maptiler_API_Code');
</script>
<script>
var autocomplete = new kt.OsmNamesAutocomplete(
'search2', 'https://geocoder.tilehosting.com/', '#My_Maptiler_API_Code');
</script>
<!--GET INFO-->
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML =
this.responseText;
}
if (this.readyState == 4 && this.status == 429) {
document.getElementById("result").innerHTML =
"Servidor sobrecargado, inténtelo más tarde."
}
};
xhttp.open("GET", "http://router.project-osrm.org/table/v1/driving/{longitude1},{latitude1};{longitude2},{latitude2}", true);
xhttp.send();
}
</script>
First, I need to get the coordinates of the places from the inputs with the help of the autocomplete function.
Currently, when the user clicks on one of the suggested places on the list, just the name item gets written in the input box. Instead, I would like to get the GPS coordinates written, not the name, so that I can use them to send the HTTP request (next step).
What is being written when I click:
What I need for the next step:
Btw, I have seen some answers in other related questions inviting to use "Nominatim". As I said, I am currently using "OSMNames", is there any difference? Should I change my geocoder?
Then, I would also need to get these coordinates in the HTTP GET request, as shown on the code.
And finally, I would like to get just one of the items from the OSRM response, the distance. Since otherwise, I would just get the entire response.
I have literally no idea on how to do any of the stated steps since I am a student that is still getting started on this area.
If only you could lend me a hand here it would be excellent.
I try to avoid putting all the code here because I find it confusing when reading but should you need the rest of the code for any reason, please let me know!
Thanks for your help! :)
Related
My project is on JSF2 and I am trying to pull some reference data from the Server to be used in an Input (text) field on the front end.
Using the following link as the starting point
https://www.w3schools.com/howto/howto_js_autocomplete.asp
Instead of using the Array of fixed values (Strings), I want to fetch the data dynamically from the Server. Here is my code that attempts to achieve the purpose:
var constituencies;
function retrieveConstituencies(){
/* Load constituencies dynamically */
var mde=document.getElementById("mode").value;
alert("mode is "+mde);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
constituencies = this.responseText;
alert(constituencies);
}
};
xhttp.open("GET", "/NominateServlet?mode="+mde, true);
xhttp.send();
}
And here is my final code that calls the autocomplete function (similar to the example in the link provided above)
autocomplete(document.getElementById("vsInput"), constituencies);
I am badly stuck on this problem from last 3 days and the autocomplete method just does not takes the AJAX values. If anyone has solution for this, kindly share.
PS: I am not using PrimeFaces or JQuery because I want to use vanilla technologies.
Many Thanks
XMLHttpRequest makes an asynchronous request. The "autocomplete" function is called before the request completed and the "constituencies" variable is set. You should call the "autocomplete" function after request to API is completed. Try like this:
if (this.readyState === 4 && this.status === 200) {
const items = JSON.parse(this.responseText);
const input = document.getElementById("vsInput");
autocomplete(input, items);
}
I'm building a web site which lets users post requests on site and others to respond. I have built an app-like form to collect information. In that form I need to display 3 pages.
So I have created one page with the from and and a JavaScript file to handle these 3 pages. Other form-pages are designed separately (HTML only).
I'm planning to load the other two pages into that 1st page with XMLHttpRequest and it works.
But I need to take 3rd page into the 1st form-page (display the 3rd page of form) and change the innerHTML of that 3rd page. I tried it with
function setFinalDetails() {
document.getElementById("topic").innerHTML = object1.start;
}
//creating a XMLHttpObject and sending a request
//requiredPage is the page we request.
//elementId is the element we need to display
function requestAPage(requiredPage) {
selectElementId(requiredPage);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
m = xhttp.responseXML;
y = m.getElementById(elementId).innerHTML;
document.getElementById("hireForm").innerHTML = y;
//m is a global variable
//m is the object recieved from XMLHttpRequest.
//it is used to change the innerHTML of itself(m) and display.
//y is displaying the 3rd page in the form-page one("id =hireForm")
return m;
}
};
xhttp.open("GET", requiredPage, true);
xhttp.responseType = "document";
xhttp.send();
}
but that gives an error:
Cannot set a .innerHTML property of null
find my work on https://github.com/infinitecodem/Taxi-app-form.git
It it hard to help you in detail because we do not have a way to reproduce your error and test your code. I can suggest you to use a service like plunker to share your code. I do not know if this service will support to do some xhrRequest on other files in its working tree, you can try.
Your error message seems to reveal that one of your document.getElementById(...) is returning null instead of the html elt you want (so the id do not exist in the page).
But again without a way to test, it is hard to help you more sry. I really encourage you to try to share a link to a service (like plunker, etc) that will help others to play with your use case.
I have an application that gathers live JSON data every second from another server via XMLHttpRequest. After checking the Networks panel on Chrome, I have found that the size of each packet is about 697 bytes. I am unsure whether this is a high or a low number, and whether there are any potential problems running my application like so.
Example:
var exhaitch = new XMLHttpRequest();
var exlink = "wheremydatais.com";
exhaitch.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
console.log(JSON.parse(this.responseText));}
}
exhaitch.open("GET", exlink, true);
exhaitch.send();
This javascript code is put inside an interval that is set to run every 1.5 seconds. The console log contains the updated data I want to use in my application.
I understand that ideally this would have been done using Node.js and Socket.io. However, much of this application has already been built over LAMP stack. So I am wondering what my options are if this method is unsustainable over the long term.
One thing I have looked into recently is socket.io without Node. Though I am still unclear how to go about that.
I think this is more preferable and will scale better:
function getMyData(){
var exhaitch = new XMLHttpRequest();
var exlink = "wheremydatais.com";
exhaitch.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
console.log(JSON.parse(this.responseText));
getMyData();
}
}
exhaitch.open("GET", exlink, true);
exhaitch.send();
}
First of all I'm sorry for the really vague title, but I have no clue how to name the title. So if someone has a better name, please let me know and I'll edit it.
I have made some sort of a calculator, where the cost of ownership gets calculated. The input of values comes from the user or a preset from a database. The presets can be chosen with a select, and I use the onchange-event to change input data.
<select id="myID" onchange="getPreset(this.value)">
<option>Some options...</option>
</select>
In the getPreset() function I do some stuff + I call another function which I use to get the data from a database via JSON.
function getInfo(name){
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var info = JSON.parse(xmlhttp.responseText);
//process data
calculate();
}
}
xmlhttp.open("GET", "myphppage.php?name="+name, true);
xmlhttp.send();
}
This is how my code is now and it works fine and as it should. But before I had placed calculate(); after xmlhttp.send();, which didn't work as it should have. The data got calculated only AFTER I chose another option. For example: first time I chose option 1 - nothing happens. Second time I chose option 2 - data gets calculated like option 1 is chosen.
I get that it was just the wrong place to put the function, but here's what I found strange: if I put an alert before the calling of the function, the data did get calculated. So my code was as following (so you can see it visually):
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var info = JSON.parse(xmlhttp.responseText);
//process data
}
}
xmlhttp.open("GET", "myphppage.php?name="+name, true);
xmlhttp.send();
alert("make it work.");
calculate();
}
As I have no idea why this is and I'm curious to know, I'm asking it here. I hope someone can help me explain.
It's because of everything is asynchronous. While the alert pops up you (eventually) get the data and it's calculated correctly. That's why it works. If the connection is veeeery slow or you click 'ok' on the alert button extremely fast, it might fail. That's why you should put it in the correct place :)
I'm writing a Chrome extension that searches for posts in a Google Group whose subject lines contain a given character string. From the browser, using the search query "subject:", I get the search results: either 0 results or > 0 and I take different actions depending on whether results come up. The wrinkle is that if I simply fetch the page data for the results page using, say,
try
{
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
}
catch (e)
{
console.log(e);
return;
}
if (request.status == 200)
{
var tmp = request.responseText;
}
I just get obfuscated data and can't read it. If I can get a Document object back, then I can search for a certain classname, with something like doc.getElementsByClassName, that exists if and only there are non-zero results from the search.
Here's how to turn the responseText to a dom....
var page = document.implementation.createHTMLDocument("");
page.documentElement.innerHTML = request.responseText;
// Now you can find things
var thing = page.documentElement.querySelector('#find');
...but this won't always be enough for some pages as they are ajax driven and the new Google Groups is for sure.
So this page is just the frame for all the other stuff the js is going to get when the page is loaded.
Somtimes you can figure how to replicate the ajax request the page makes and replicate it by looking at the Network panel in the WebInspector and watch what happens when you press the search button.
But Google Groups 2 is doing some funky stuff and I wouldn't have a clue ;)
There's other things you can do like override XMLHttpRequest and monitor what calls it and what it does when the ready state changes to 4 or monitor the onload. And use that info to try and figure out what function processes the responseText and sometimes find what you need that way. But I can't find my code for that at the moment and dont really feel inclined to do it for this as I know its not going to be pretty ;)
Good Luck.