Skip to main content
John_Allred
Inspiring
March 17, 2020
Question

Use geoLocation Lat/Lon to query database

  • March 17, 2020
  • 2 replies
  • 2288 views

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
 
 

 

This topic has been closed for replies.

2 replies

BKBK
Community Expert
March 26, 2020

@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>

 

 

John_Allred
Inspiring
March 28, 2020

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

Charlie Arehart
Community Expert
March 25, 2020

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)
John_Allred
Inspiring
March 25, 2020

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

Charlie Arehart
Community Expert
March 25, 2020

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)