get latitude and longitudefrom city name using HTML,js in bing map - javascript

I need to get latitude and longitude by city name using bing map. Here is my code.
function Geocode() {
//Create Bing Maps REST Services request to geocode the address provided by the user
var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/"
+ "Colombo"
+ "?output=json"
//Set the callback function
+ "&jsonp=GetLocationCoordinates"
+ "&key=Ai5r7K1Jy95BfrDbOV9PPvoBqYicNNe3Bapi7PczGda-l30CjbpHeLnK8XQmYcKl";
//Submit the request
MakeServiceRequest(geocodeRequest);
}
function MakeServiceRequest(request) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
GetLocationCoordinates();
}
function GetLocationCoordinates(geocodeResponse) {
if(geocodeResponse==null) document.getElementById("txt").innerText = "This is null";
if (geocodeResponse &&
geocodeResponse.resourceSets &&
geocodeResponse.resourceSets.length > 0 &&
geocodeResponse.resourceSets[0].resources &&
geocodeResponse.resourceSets[0].resources.length > 0) {
setLoc(geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[0], geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[1], 10);
}
else {//The location could not be geocoded
var md = new Windows.UI.Popups.MessageDialog("The location could not be geocoded");
md.showAsync();
}
}
But in here it never called function GetLocationCoordinates(geocodeResponse). How can I make to call it.?

Probably because you are running this from the local context. Create an iframe and add the code in that resulting html file.
I've wrapped the code in a namespace. This way you can define where the function will be called rather than sticking your functions in the global namespace. Note I commented out your direct call of the function, its not needed.
Create a /pages/map/map.html, map.js, map.css (in other words, create a /pages/map and right click on it and select add new item and choose 'page' type named map)
In map.js include the following after 'use strict', or include in another javascript file. It's up to you.
WinJS.Namespace.define("LocationServices", {
GetLocationCoordinates: function (geocodeResponse) {
if (geocodeResponse == null) document.getElementById("txt").innerText = "This is null";
if (geocodeResponse &&
geocodeResponse.resourceSets &&
geocodeResponse.resourceSets.length > 0 &&
geocodeResponse.resourceSets[0].resources &&
geocodeResponse.resourceSets[0].resources.length > 0) {
setLoc(geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[0], geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[1], 10);
}
else {//The location could not be geocoded
var md = new Windows.UI.Popups.MessageDialog("The location could not be geocoded");
md.showAsync();
}
},
Geocode: function () {
//Create Bing Maps REST Services request to geocode the address provided by the user
var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/"
+ "Colombo"
+ "?output=json"
//Set the callback function
+ "&jsonp=LocationServices.GetLocationCoordinates"
+ "&key=Ai5r7K1Jy95BfrDbOV9PPvoBqYicNNe3Bapi7PczGda-l30CjbpHeLnK8XQmYcKl";
//Submit the request
this.MakeServiceRequest(geocodeRequest);
},
MakeServiceRequest: function (request) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
// GetLocationCoordinates();
}
});
In turn load map.html (which includes a reference to map.js and has your input id='txt')
<iframe src="ms-appx-web:///pages/map/map.html"></iframe>

Related

Get geolocation on submit in Google Forms using Google Script

I have a Google Form where I want to get the user geolocation along with the inputs.
Currently, I'm able to get it by making the user click on a url after he submits the answers. This is the code in Google Script that does it:
function doGet() {
return HtmlService.createHtmlOutputFromFile("Index");
}
function getLoc(value) {
var destId = FormApp.getActiveForm().getDestinationId() ;
var ss = SpreadsheetApp.openById(destId) ;
var respSheet = ss.getSheets()[0] ;
var data = respSheet.getDataRange().getValues() ;
var headers = data[0] ;
var numColumns = headers.length ;
var numResponses = data.length;
var c=value[0]; var d=value[1];
var e=c + "," + d ;
if (respSheet.getRange(1, numColumns).getValue()=="GeoAddress") {
respSheet.getRange(numResponses,numColumns-2).setValue(Utilities.formatDate(new Date(), "GMT-3", "dd/MM/yyyy HH:mm:ss"));
respSheet.getRange(numResponses,numColumns-1).setValue(e);
var response = Maps.newGeocoder().reverseGeocode(value[0], value[1]);
f= response.results[0].formatted_address;
respSheet.getRange(numResponses,numColumns).setValue(f);
}
else if (respSheet.getRange(1,numColumns).getValue()!="GeoAddress") {
respSheet.getRange(1,numColumns+1).setValue("GeoStamp");
respSheet.getRange(1,numColumns+2).setValue("GeoCode");
respSheet.getRange(1,numColumns+3).setValue("GeoAddress");
}
}
And the Index.html file:
<!DOCTYPE html>
<html>
<script>
(function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
})()
function showPosition(position){
var a= position.coords.latitude;
var b= position.coords.longitude;
var c=[a,b]
getPos(c)
function getPos(value){
google.script.run.getLoc(value);
}
}
</script>
</html>
Instead of making the user click on a url, I want the geolocation to be automatically inputed into the response sheet as the user submits the form. I'm able to make the getLoc function run on a submit trigger, however the html function doesn't run. I believe it might be because the doGet function is already a trigger, but it requires a browser page to be opened in order to run. If that's the case, the ideal solution would be to redirect the browser to the Google Script url after the user submits it, but I can't seem to find a way to do it. Is this the correct approach and how can I make it work?
Thanks in advance!
Maybe this works: https://www.youtube.com/watch?v=J93uww0vMFY
Tutorial on Geotagging (Geo-stamp and Time-stamp) google forms.
Add info on Latitude, Longitude, and Address (Street name and number, city, state, zip code, and country) of a device submitting google forms. Linking user’s location within google forms.
Google forms integration with google maps.
Links to download the scripts are given below:
Code.gs : https://www.youtube.com/redirect?v=J93uww0vMFY&event=video_description&q=https%3A%2F%2Fdrive.google.com%2Fopen%3Fid%3D1D4vTzUGZAf3_ZDVMeW760i1KoZCn37un&redir_token=VQ2rLeQvyQea-mq9_kGhh_Kxihd8MTU5MTgxOTM2OEAxNTkxNzMyOTY4
Index.html : https://www.youtube.com/redirect?v=J93uww0vMFY&event=video_description&q=https%3A%2F%2Fdrive.google.com%2Fopen%3Fid%3D1mYZGYNrXNOxUD8DlDmRdBajy1nc3FKtw&redir_token=VQ2rLeQvyQea-mq9_kGhh_Kxihd8MTU5MTgxOTM2OEAxNTkxNzMyOTY4

Using ACF to grab Lat/Long based on other Address Information?

So I created AFC fields for street address, city, state, and zip and then I am using Google Maps to take the information in those fields and then populate two other ACF fields with the lat and long for that address. The issue I am having is that when I put in the address fields and click the publish/update button it does not grab the lat/long right away. When I click it a second time is when the grabs the lat/long and populates those ACF fields. This only occurs when I add a new address. If I use an address that has already been used on another post and reuse that same one for a new post it does grab the lat/long on first try. So based off of that I assume that the first click is grabbing the lat/long and the second click is being used to populate the lat/long fields.
But what I need to accomplish is that both of those steps(grabbing lat/long and populating lat/long fields) to happen on the same publish/update button click. Below is the code I currently am using:
add_action( 'post_submitbox_start', 'qd_fake_publish_button' );
function qd_fake_publish_button()
{
$screen = get_current_screen();
if( ($screen->parent_base == 'edit') && ( $screen->id == 'opportunity' ))
{
print '<button id="acquireLatLong" class="button button-primary button-large">Publish</button>';
}
}
add_action( 'admin_print_footer_scripts', 'project_pins_save_post', 11);
function project_pins_save_post() {
$screen = get_current_screen();
if( ($screen->parent_base == 'edit') && ( $screen->id == 'opportunity' ))
{
$script = '
<script type="text/javascript" src="MY_GOOGLE_API_KEY"></script>
<script type="text/javascript">
function AcquireLatLont() {
var mygc = new google.maps.Geocoder();
var qd_street = document.getElementById("acf-field_5abe83dfda81b").value;
var qd_city = document.getElementById("acf-field_5abe4bea43cc3").value;
var qd_state = document.getElementById("acf-field_5abe4bf543cc4").value;
var qd_zip = document.getElementById("acf-field_5abe4bfb43cc5").value;
var address = qd_street + ", " + qd_city + ", " + qd_state + " " + qd_zip;
mygc.geocode({ "address": address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("acf-field_5abe845fda81c").value = results[0].geometry.location.lat();
document.getElementById("acf-field_5abe846ada81d").value = results[0].geometry.location.lng();
document.getElementById("publish").click();
} else {
alert("Geocoder failed due to: " + status);
}
});
return false;
}
</script>
<script type="text/javascript" >
jQuery( document ).ready(function( $ ) {
$("#acquireLatLong")[0].textContent = $("#publish")[0].value;
$("#acquireLatLong").click(function() {
AcquireLatLont();
});
});
</script>
';
echo $script;
}
}
Haven't really worked with populating ACF fields dynamically before, so not sure where this code snippet is messing up.

Context When Loading JS File Dynamically [duplicate]

I am a JavaScript newbie and learn by working on a pure JavaScript "project" that calculates mathematical functions. It all works well. Now, as a further step, I want to make the messaging multilingual. The code should be capable of loading the appropriate language file at runtime. For the dynamic loading issue, I read and found solutions on Web pages like this one.
Before writing the dynamic code, I loaded it statically and the test code worked well. The code I am asking for help about is just making the minor difference of loading a "script" element.
The code where I run into problems is the this.getString function, where it is not possible to access the de element in the language file. At line console.log(eval(language, tag));, I get the error message "Uncaught ReferenceError: de is not defined".
//File: Utils/Lang/js/FileUtils.js
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
loadFile("js/resources/lang.de.js");
return;
} ()
this.getString = function(tag, strDefault) {
console.log("getString(" + tag + ", " + strDefault + "): ");
console.log("getString(...): document = " + document);
console.log("getString(...): eval(" + language + ", " + tag + ") = ");
console.log(eval(language, tag));
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined')
? strDefault
: eval('en.' + tag);
}
}
}
The static test code that works is not included, where I can access the de element.
My question: How to load the language file properly so that the de tag is accessible?
Thank you for your help!
//File: Utils/Files/js/FileUtils.js
function loadFile(filepathname) {
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
console.log("loadFile(\"" + filepathname + "\"): document = " + document);
}
//File: Utils/Lang/js/resources/lang.de.js:
de = {
pleaseWait: "Bitte warten..."
};
//File: Utils/Lang/js/resources/lang.en.js
en = {
pleaseWait: "Please wait..."
};
//File: Utils/Lang/js/TestLanguage.js:
function output() {
console.log("output()");
var codes = ['de', 'en'];
for (var i = 0; i < codes.length; i++) {
var translator = new Language(codes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
<!--File: Utils/Lang/TestLang.html:-->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="js/Language.js"></script>
<script type="text/javascript" src="js/TestLanguage.js"></script>
</head>
<body>
<button name="outputButton" onclick="output();">Click</button>
<br>Please press [F12] so that you can see the test results.
</body>
</html>
When you add the script tag to your document, it is not loaded synchronously. You need to wait for the file to be loaded before you can use the code that was in it.
you may be able to redesign your code to use a script.onload callback:
var reference = document.createElement('script');
// ...
reference.onload = function() {
alert("Script loaded and ready");
};
but for this scenario, if you don't have many language string you may be best to just load them all statically.
How to dynamically load a script file (the most basic version, also there are multiple options to this):
function loadScriptFile(scriptPath, jsFile, callBack)
{
var scriptTag = document.createElement("script"); //creates a HTML script element
scriptTag.language = "JavaScript"; //sets the language attribute
scriptTag.type = "text/javascript";
scriptTag.src = scriptPath + jsFile + ".js"; //the source
if (callBack)
{
scriptTag.onload = callback; //when loaded execute call back
}
var scriptTagParent = document.getElementsByTagName("script")[0];
if (scriptTagParent)
{
scriptTagParent.parentNode.insertBefore(scriptTag, scriptTagParent);
}
else
{
document.body.appendChild(scriptTag);
}
}
How it works:
Run loadScriptFile("scripts", "math", startProgram). The first two arguments will point to your file and folder. The last argument is a callback function. When defined this will be executed once the script tag has finished loading and the script is available in the global scope. The script will be dynamically added to your page. If there is a script element present on the page, this will be added before that (to keep the mark up nice). If not it will be appended to the body. (this is only visual).
The callback part is the most interesting. Since your script will now be asynchronical, you'll need to use callback to tell your program that the necessary files are loaded. This callback is fired when the script file is loaded, so you won't get script errors.
Just a basic example of what I meant in my comment:
This is not an answer to your question, it's an alternative way (I think it's better to manage). Pure Javascript (with help of XML)
XML-file: language.xml
Basic XML structure:
<language>
<l1033 name="english" tag="en-US">
<id1000>
<![CDATA[
Hello World!
]]>
</id1000>
</l1033>
<l1031 name="german" tag="de-DE">
<id1000>
<![CDATA[
Hallo Welt!
]]>
</id1000>
</l1031>
</language>
What did I do:
I constructed a root element called language. Within that wrote two language strings called l1033 for English and l1031 for German. Note that a letter is prepended before the language code. XML will throw an error when a tag starts with a digit. a CDATA block is used to prevent any problems with special characters.
Now the loading will be done by AJAX:
var xmlLoader = new XMLHttpRequest();
xmlLoader.onreadystatechange = trackRequest; //event to track the request, with call back
xmlLoader.open("get", "language.xml", true); //set asynchronous to true
xmlLoader.send(null);
function trackRequest()
{
if (this.status == 200 && this.readyState == 4) //all is good
{
globalLanguageFile = this.responseXML;
startProgram(); //fictive function that starts your program
}
}
Now the XML is loaded. How to load strings from it?
function loadLanguageString(code, id, fallback)
{
var word = fallback;
if (globalLanguageFile.getElementsByTagName("l"+code).length > 0)
{
if (globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id).length > 0)
{
//found the correct language tag and id tag. Now retrieve the content with textContent.
word = globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id)[0].textContent;
}
}
return word; //when failed return fall back string
}
How to call the function:
loadLanguageString(1031, 1000, "Hello World!");
I found the right answer to my question using the info from GarethOwen. Here are the code modifications I had to do:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Arrays/js/ArrayUtils.js"></script>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="../Logic/js/LogicalUtils.js"></script>
<script type="text/javascript" src="js/LanguageUtils.js"></script>
<script type="text/javascript" src="js/TestLanguageUtils.js"></script>
</head>
<!-- body onload="load(null, '../Maths/js/resources')" -->
<body onload="load();">
<button onclick="output();">Click</button><br>
Please press [F12] so that you can see the test results.
</body>
</html>
TestLanguage.html: Augmented the body tag
<body onload="load()">
TestLanguage.js:
2a. Added the load() function requested by the HTML page now:
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < codes.length; i++) {
new Language(codes[i]);
}
}
2b. Using the global gCodes variable also in the output() function
Language.js: To test the whole better, I made the code in the function Language a little bit more elaborate by changing the line in the constructor in function Language(language) to:
// Load the proper language file:
if (eval("gLoaded.indexOf('" + language + "') < 0")) {
loadFile("js/resources/lang." + language + ".js");
gLoaded[gLoaded.length] = language;
}
Thank you for your support! :-)
//Lang/js/Lang.js:
"use strict";
/**
* Object for multilingual message handling.
*
* #param language
*/
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
switch (language) {
case "de":
loadFile("js/resources/lang.de.js");
break;
case "tr":
loadFile("js/resources/lang.tr.js");
break;
default:
loadFile("js/resources/lang.en.js");
}
return;
}()
/**
* Returns the language of that object.
*
* #returns The language
*/
this.getLanguage = function() {
var strLanguage;
switch (language) {
case "de":
strLanguage = "German";
break;
case "tr":
strLanguage = "Turkish";
break;
default:
strLanguage = "English";
}
return strLanguage;
}
/**
* Returns the language code of that object.
*
* #returns The language code
*/
this.getString = function(tag, strDefault) {
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined') ? strDefault : eval('en.' + tag);
}
}
}
//Lang/js/TestLang.js:
"use strict";
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < gCodes.length; i++) {
new Language(gCodes[i]);
}
}
/**
* Object for multilingual message handling.
*
* #param language
*/
function output() {
console.log("output()");
for (var i = 0; i < gCodes.length; i++) {
var translator = new Language(gCodes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
//Utils/Files/js/FileUtils.js:
"use strict";
/**
* Object with file utilities
*
* #param filepathname
*/
function loadFile(filepathname) {
var methodName = "loadFile(" + filepathname + "): "
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
reference.onload = function() {
console.log(methodName + "onload(): Language script loaded and ready!");
}
}
Here is the console output:
Here is the output:
load()
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!
output()
output(): in German: Bitte warten...
output(): in English: Please wait...
output(): in Turkish: Lütfen bekleyiniz...
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!

Dynamic script tag using server active notification

When using server and client in same machine by ajax connectivity it shows the inactive state of server. On using dynamic script tag it doesn't reflect the inactivness of server. How could this be resolved?
we have included these functions in a .js file.
function JSONscriptRequest(fullUrl) {
this.fullUrl = fullUrl;
this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
this.headLoc = document.getElementsByTagName("head").item(0);
this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}
JSONscriptRequest.scriptCounter = 1;
JSONscriptRequest.prototype.buildScriptTag = function () {
this.scriptObj = document.createElement("script");
this.scriptObj.setAttribute("type", "text/javascript");
this.scriptObj.setAttribute("charset", "utf-8");
this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
this.scriptObj.setAttribute("id", this.scriptId);
}
JSONscriptRequest.prototype.removeScriptTag = function () {
this.headLoc.removeChild(this.scriptObj);
}
JSONscriptRequest.prototype.addScriptTag = function () {
this.headLoc.appendChild(this.scriptObj);
}
and used the following code in jsp page
// The web service call
var req = <<<url of the service which resides in different server>>>&callback=<callback function>;
// Create a new request object
bObj = new JSONscriptRequest(req);
// Build the dynamic script tag
bObj.buildScriptTag();
// Add the script tag to the page
bObj.addScriptTag();

delay in dynamic loading of external Javascript(JSON) file for Phonegap

im trying to load a external js (json) file (PhoneGap app) whose structure is like
var localString ={
"tag1": "Username",
"tag2": "Password",
"submit": "Submit"
}
and using the below code to load it at runtime, the newlocale variable holds the name of the file to be loaded for eg: if locale is english-USA then var resourcePath = en-US.js. The issue is the first time i run this code i get this error "ReferenceError: localstring is not defined" , but it loads the external strings the second time i load it. In between i am calling the external file using "select" tag in html5. Can someone provide some insights on where im going wrong or any pointers to overcome this issue.
var newlocale = window.DeviceCulture.get();
local(newlocale);
function local(lang) {
try {
var resourcePath = lang + '.js';
var scriptEl = document.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = resourcePath;
alert(resourcePath);
document.getElementsByTagName("head")[0].appendChild(scriptEl);
//$('head').append(scriptEl);
//var localString = window.localString;
document.getElementById("07").value = localString['submit'];
} catch (e) {
errorEvent(e);
}
}
Okay I believe the root cause of your problem is that you are appending the tag for the .js file into the head after the page is already loaded. When you first load a page the script tages are downloaded and interpreted in order so b can depend on a. However, the way you are doing it is non-blocking so that the script you load is not fully loaded by the time you get to the next line in your code which tries to access "localString".
To solve this I'd restructure your code somewhat. First forget about making local files JavaScript. Just make them plain text .json files. For example:
{
"tag1": "Username",
"tag2": "Password",
"submit": "Submit"
}
Then I'd load that file using XHR instead of script tag insertion. Something like:
var newlocale = window.DeviceCulture.get();
var localString;
local(newlocale);
function local(lang) {
try {
var resourcePath = lang + '.json';
var request = new XMLHttpRequest();
request.open("GET", resourcePath, true);
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
localString = JSON.parse(request.responseText);
// at this point localString is loaded with the new language
document.getElementById("07").value = localString['submit'];
}
}
}
request.send();
} catch (e) {
errorEvent(e);
}
}
and that should take care of things.

Categories

Resources