• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

Use geoLocation Lat/Lon to query database

Contributor ,
Mar 17, 2020 Mar 17, 2020

Copy link to clipboard

Copied

As a user of my web site drives around, her latitude/longitude changes. I would like for her to be able to click a button and have her current coordinates (which are captured through JS in a geoLocation script) passed to the query below through a form as #userLat# and #userLon#. The resultset would be displayed in a new cfml template.

 

If I have to use the JS variables within one of the JS scopes, can I create the form using javascript and pass the variables to the query that way?

 

Perhaps the question is as simple as, can a javascript variable be made available for use in a cfml template? And, if so, how?

 

Sounds simple to some, I'm sure, but I've had only cursory dealings with javascript and none with Ajax. I'm hoping for a conceptual overview that can lead me to focused self-education. Your advice is welcome.

~John

 

========================

SELECT MID, AptName, round(calc_dist,2) AS Distance
FROM (
     SELECT MID, AptName, sqrt(power((#userLat# - lat),2)
     + power((#userLon# - lon),2)) * 62 as calc_dist
     FROM test_maps
) AS calculated
ORDER BY calc_dist
LIMIT 3

 

This yields:

MIDAptNameDistance
116Depot 160.10
10Briq on 4th Street0.17
3Town Square Apartments0.46
 
 

 

TOPICS
Advanced techniques , Asynchronous

Views

1.8K

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Mar 25, 2020 Mar 25, 2020

Copy link to clipboard

Copied

Jack, what you're wanting is an ajax mechanism to call your CF page, passing in data obtained from javascript, right? In that case, the most basic tool for that is the javascript xmlhttprequest feature (though depending on any js framework you may have installed, they offer still other ways. And in fact there are CF tags and functions that can help also.)

 

But sticking with the basics, which it sounds like you want, I would point you to 2 pages from the w3schools site. They are brief and both explain things and offer live examples. Do read both:

 

https://www.w3schools.com/xml/ajax_xmlhttprequest_create.asp

https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

 

If after reading those, and trying the examples, and then using similar ones on your own site to call your own page, if you still need more help, either ask here (clarifying what is amiss), or maybe this will be enough to set you on a journey of finding more elaborated discussion of the topic, which may show examples more suited to your need.

 

Do let us know if this helps.


/Charlie (troubleshooter, carehart.org)

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Contributor ,
Mar 25, 2020 Mar 25, 2020

Copy link to clipboard

Copied

Thanks, Charlie. Having precious little experience with either JS or Ajax, I figured out how to get a user's location (https://www.tutorialrepublic.com/html-tutorial/html5-geolocation.php). That makes latitude and longitude variables available, and those variables are what I'd want to pass along to another CF template to execute a query. They exist in either a local or global scope within the JS. To utilize either of the objects you linked to, do I need to place them within the proper scope in that existing JS code? Or would they go into an Ajax script?

 

I guess my question is what is the context where I'd implement them?

 

Thanks,

John

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Mar 25, 2020 Mar 25, 2020

Copy link to clipboard

Copied

I don't think it will matter at all. Have you tried it? 🙂

 

Or is it that you prefer to understand everything first? I understand, though I'd propose that will really slow you down. Coding is like painting, or sports. You need to just get out there and try. 🙂

 

Or perhaps the issue is that you don't have a dev environment and are therefore reluctant to change production code on the fly (as indeed, one should be). In that case, can you create a test page and play with things there?

 

Finally, I'm noticing that while your original post here (and previous ones) indicated as being from Jack_Allred2, it now shows your username as John_Allred. I guess you changed your username? It's reflected that way now in the UI here for all your messages in this thread. Just sharing that in case others read what I wrote, and wonder why I had addressed you as "Jack" before. 🙂


/Charlie (troubleshooter, carehart.org)

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Contributor ,
Mar 25, 2020 Mar 25, 2020

Copy link to clipboard

Copied

Yep. I changed my user name on my profile, which I created at a time when I commonly used a nickname. Just housecleaning.

 

As for trying things as you recommend, I have a good coding environment, but I don't favor flopping around, trying things that I simply can't conceptualize. Javascript is among those things, and I have no clue how Ajax relates to it. And please don't think I haven't spent time trying to educate myself. I wasted a bunch of money on an absolutely horrible book on Ajax, when I thought that would be the path to a solution. I struggle with javascript, as well, because 99.99% of books and online resources I've investigated seem to tour through an alphabetical list of features with—are you ready for it?—absolutely no context, no overview, no explanation of how things work as a system. Sorry if this sounds like a rant.

 

I have, actually, tried quite a bit of js code. I have not yet been successful in passing the two js variables I mentioned previously to any other code. I don't have much grasp of scopes in js. Maybe I'm looking at JSON? I just don't know.

 

Thanks for responding!

~john

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Mar 26, 2020 Mar 26, 2020

Copy link to clipboard

Copied

This is not the answer that you want to hear, but if you want to support JavaScript solutions, you will eventually have to be able to conceptualize them. This is a difficult task for a lot of CF (and other server-side) developers. But you're going to have to bear down on them until you finally understand them. Once you do understand them, you'll look back in surprise that it took you that long. They're not really that difficult, they're just different.

 

AJAX is just kind of a vague acronym that, paraphrased, means using JavaScript to invoke remote APIs and send/receive data instead of relying on your server to do that on a page change. For example, in the "old days", a user might fill out a form, then submit the page back to the server, which would then use CFHTTP or whatever to send data to another server, which would respond with XML or whatever back to your server. Your server would then read the data and figure out what to display next. (Note the liberal use of "whatever" there, it could be practically any readable data format.) Nowadays, many web apps use JavaScript to do this instead, so that users don't actually have to leave the page they're on. Gmail is a great example of this. You go to one URL, and stay there all day. But you send and receive mail while you're still at that URL. This requires client-side programming your browser can run, rather than server-side programming that runs somewhere else. The "X" in AJAX stands for XML, but hardly anyone uses XML anymore because it's painful and annoying. Most people use JSON (JavaScript Object Notation), which is just a way to express a JavaScript object in a string that can be passed back and forth between your JavaScript program to a URL somewhere. Your JS program will, perhaps, retrieve a JSON string from a URL using XMLHttpRequest, evaluate it as an object, read values from it, display those values within your HTML page, etc. I wouldn't bother reading a book on AJAX unless you're really, really interested in a lot of details that you probably don't really need to know.

 

Right now, there's an online tutorial called "Beginning JavaScript" that I'd recommend. Ideally, if you haven't worked with JavaScript in a while, you'd take something like this which is really a ground-up approach using modern JavaScript - which looks quite a bit different from the JavaScript I originally learned back in the old days! I don't have the URL handy - am at another computer - but you really want to start with the fundamentals, because JavaScript is quite a bit different from CF and HTML. I hope you take this in the spirit in which it's intended - not as insulting in any way, just as helpful advice. (I'm busy relearning JavaScript myself, just because it's changed so much!)

 

Dave Watts, Eidolon LLC

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Mar 26, 2020 Mar 26, 2020

Copy link to clipboard

Copied

I guess I should have been able to figure out the URL. Here it is: https://beginnerjavascript.com/

 

Dave Watts, Eidolon LLC

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Mar 26, 2020 Mar 26, 2020

Copy link to clipboard

Copied

To address your direct question, JavaScript variables in HTML exist within that HTML page as long as it's in the browser. Once you navigate to another page, that JavaScript is gone. There's no mechanism to persist JS variables beyond the lifespan of the page. (slight oversimplification, but good enough for now)

 

So, your goal as I understand it is to have a single HTML page that retrieves those variables, then have your JavaScript put them in some format that can be sent to the next page (form or URL parameters), then have the second page use CF to do something with those variables if needed, then use a second JavaScript program to do whatever else you need on the second page. A lot of the "put[ting] them in some format" bit is standard core JavaScript stuff. Of course, if the first page isn't really doing anything with the variables except sending them to the second page, you could probably retrieve them with CF, then have CF build your JS program in the second page to do what you want with them.

 

Dave Watts, Eidolon LLC

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Mar 26, 2020 Mar 26, 2020

Copy link to clipboard

Copied

@John_Allred, you asked:

Perhaps the question is as simple as, can a javascript variable be made available for use in a cfml template? And, if so, how?

 

The answer is yes. What now follows is an example based on the Javascript you referenced. 

Javascript uses the calculated latitude and longitude to populate a form. By means of a click on a button, the form is submitted and the position inserted into the database.

Note that the form is submitted to the current page (that is the meaning of  CGI.SCRIPT_NAME).

You may, for greater rigour, want to replace in your insert-query the values (#form.latitudeFormfield#,#form.longitudeFormfield#) with

(<cfqueryparam value="#form.latitudeFormfield#" cfsqltype="cf_sql_float">, <cfqueryparam value="#form.longitudeFormfield#" cfsqltype="cf_sql_float">) 

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Current Position</title>
<script>
	var lat=0;
	var long=0;
    function showPosition() {
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
            	
            	lat = position.coords.latitude;
            	long = position.coords.longitude;
            	document.getElementById("latitudeFormfield").value = lat;
            	document.getElementById("longitudeFormfield").value = long;
            	
                var positionInfo = "Your current position is (" + "Latitude: " + lat + ", " + "Longitude: " + long + ")";
                document.getElementById("result").innerHTML = positionInfo;
            });
        } else {
            alert("Sorry, your browser does not support HTML5 geolocation.");
        }
    }
    function savePosition() {
    	document.getElementById("locationForm").submit();
    	alert("Position saved.")
    }
</script>
</head>
<body>	 
    <!---Position information will be inserted here---> 
    <cfif isDefined("form.fieldnames")>
    	 <!---<cfdump var="#form#">--->
    	 <cfquery datasource="your_datasource_name">
    	 	INSERT INTO TABLE_NAME (latitude, longitude)  
            VALUES (#form.latitudeFormfield#, #form.longitudeFormfield#)
    	 </cfquery>
    </cfif>
    <cfoutput>      	
        <form name="locationForm" id="locationForm" method="post" action="#cgi.script_name#">
        	<input name="latitudeFormfield" id="latitudeFormfield" type="hidden">
        	<input name="longitudeFormfield" id="longitudeFormfield" type="hidden">
        </form>      
    </cfoutput>
      <button type="button" onclick="savePosition();">Save Position</button>
    
    <!---Position information will be shown here--->
    <div id="result">
    </div>
    <button type="button" onclick="showPosition();">Show Position</button>
</body>
</html>

 

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Contributor ,
Mar 28, 2020 Mar 28, 2020

Copy link to clipboard

Copied

LATEST

Thanks, BKBK!

 

Substituting a SELECT for an INSERT, this appears to be exactly what I'm looking for. I have several other ToDos ahead of this right now, but I'll report back on my success or failure.

 

Thanks!

John

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Resources
Documentation