HTML5 Geolocation + javascript help needed - geolocation

I want to make use of html5 geolocation and make use of the latitude and longitude for php.
If the user gives permission to give his location, the function needs to be called.
I want to refesh the page partly by taking information of this page:
example.php?latitude=xxxx&longitude=xxx
I already know how to refresh a div with a page with this:
$('#test_content').load('example.php);
but how do I get it work this way
<script>
getLocation();
$('#test_content').load('example.php?latitude=' + position.coords.latitude);
</script>
I am very bad in javascript and thats my big problem.
I know I am making big mistakes but I don't know what..
This is the code I use for geolocation:
// JavaScript Document
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function showError(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
x.innerHTML="User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML="Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML="The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML="An unknown error occurred."
break;
}
}

for your script you'll need to cut out these line of the first script - $('#test_content').load('example.php?latitude=' + position.coords.latitude);
and insert int in the showPosition function instead all the other stuff you've got there between the function brackets.

Related

Appcelerator - Getting geolocation information and turning into a URL

I'm still very new to appcelerator but I'm trying to do a small experiment with geolocation. I have some code similar to below, which returns the long and lat to the console. What I would like to is get the long and lat and append them to a URL, e.g http://www.mywebsite.com/lat/long.
I've tried creating a simple alert to show me the current location in the but all it says is Alert: [object GeolocationModule].
Could somebody point me in the right direction so I can learn some more? Thank you
if (Ti.Geolocation.locationServicesEnabled) {
Titanium.Geolocation.purpose = 'Get Current Location';
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
Ti.API.error('Error: ' + e.error);
} else {
Ti.API.info(e.coords);
}
});
} else {
alert('Please enable location services');
}
This is how you need to follow the API documentation:
You can have a look at the LocationResults page: https://docs.appcelerator.com/platform/latest/#!/api/LocationResults which leads you to LocationCoordinates: https://docs.appcelerator.com/platform/latest/#!/api/LocationCoordinates
There you can see, that you can use e.coords.latitude or longitude to get the values. Or have a look at the console output. It should show you a JSON output with the key-value pairs.
Once you have the values you can create a HTTP request (demo: https://docs.appcelerator.com/platform/latest/#!/guide/HTTPClient_and_the_Request_Lifecycle) and open your page:
var url = "https://www.appcelerator.com/"+e.coords.longitude+"/"+e.coords.latitude;
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this function is called when data is returned from the server and available for use
// this.responseText holds the raw text return of the message (used for text/JSON)
// this.responseXML holds any returned XML (including SOAP)
// this.responseData holds any returned binary data
Ti.API.debug(this.responseText);
alert('success');
},
onerror: function(e) {
// this function is called when an error occurs, including a timeout
Ti.API.debug(e.error);
alert('error');
},
timeout:5000 /* in milliseconds */
});
xhr.open("GET", url);
xhr.send(); // request is actually sent with this statement
or if you plan to use more request have a look at RESTe (https://github.com/jasonkneen/RESTe) which is an awesome library that makes it easy to create API requests

Arabic input fields in unity

Is there is a way to change the language of input fields in unity to Arabic?. I tried ArabicSupport and it displayed Arabic correctly but using it with input fields didn't work because
GameObject.Find("input_field")
.GetComponent<InputField>().text = Fix3dTextCS.fix(
GameObject.Find("input_field").GetComponent<InputField>().text
);
caused an error so, if I printed the input text elsewhere, it will appear correctly but how can I do it with the same input field?
input field is a little bit tricky to let it work with Arabic Support
please try this opensource asset it has an prefab for Arabic Input Field and some other UIs.
OpenSource for ArabicSupport Solution Link
OpenSource for unity asset UI Arabic Support: Link
Have you tried adding arabic font in that input.
If so, post the error message it may help to find the bug
Using Font won't help because it will only change the theme of your current Input usage but not how you use to input in the Device.
You will need to use Input.Location <- Input is static so you can access it anywhere. The only problem is, I am not sure what is the exact variable for arabic is. My best guess is Input.Location = "Arabic" or "arabic".
If you want to automatically detect their location, the GPS which will unity3d turn on by calling Input.Location.Start, and turn off by Input.Location.Stop()
Here is a sample code for you.
using UnityEngine;
using System.Collections;
public class TestLocationService : MonoBehaviour
{
IEnumerator Start()
{
// First, check if user has location service enabled
if (!Input.location.isEnabledByUser) yield break;
// Start service before querying location
Input.location.Start();
// Wait until service initializes
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
{
yield return new WaitForSeconds(1);
maxWait--;
}
// Service didn't initialize in 20 seconds
if (maxWait < 1)
{
print("Timed out");
yield break;
}
// Connection has failed
if (Input.location.status == LocationServiceStatus.Failed)
{
print("Unable to determine device location");
yield break;
}
else
{
// Access granted and location value could be retrieved
print("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);
}
// Stop service if there is no need to query location updates continuously
Input.location.Stop();
}
}

Ask for location access after initial rejection in PhoneGap apps

I'm developing cross platform applications. I'm able to request access to location using the Phone Gap API. If the user clicks okay, then I'm able to get the latitude and longitude using PhoneGap API and send it to the server.
However, I'm facing issues if the user clicks "Don't Allow" initially. After that, if he tries to refresh page, I want the device to show the popup again to request access to the location.
How do we do that in Single Page Applications?
var loadPanelMessage = ko.observable("Sipping..."),
loadPanelVisible = ko.observable(false),
lat = ko.observable(''),
lon = ko.observable('');
navigator.geolocation.getCurrentPosition(onSuccess, onError);
var onSuccess = function (position) {
lat(position.coords.latitude);
lon(position.coords.longitude);
timestamp(position.timestamp);
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
//How should I handle the error, so that it asks for Geolocation again?
}
You cannot reshow that popup, it is shown by iOS and once user click's "Don't Allow" you cannot force that popup. All you can do is to let your user know about the situation and direct the user to iOS settings to enable location services for your app.
Here is a nice read about the problem:
https://medium.com/on-startups/96fa4eb54f2c
Based on the cordova plugins here org.apache.cordova.geolocation
All you need to do is a watchPosition to check the PositionError, and use also the cordova-plugin-dialogs to show the native notification
navigator.geolocation.watchPosition((function(_this) {
return function(position) {
// Do something here
};
})(this), function(error) {
var errorButton, errorMsg, errorTitle;
errorTitle = "Location Services";
errorButton = "Ok";
if (error.code === 1) {
errorMsg = "\"AppName\" needs access to your location. Please turn on Location Services in your device settings.";
}
if (error.code === 2) {
errorMsg = "This device is unable to retrieve a position. Make sure you are connected to a network";
}
if (error.code === 3) {
errorMsg = "This device is unable to retrieve a position. Make sure you have Location Services enabled for \"AppName\"";
}
if (error.code === 1 || error.code === 2 || error.code === 3) {
return navigator.notification.alert(errorMsg, errorDismissed(), errorTitle, errorButton);
}
}, {
enableHighAccuracy: true,
maximumAge: 20000,
timeout: 10000
});

iOS / Phonegap : using FileTransfer response

first, sorry if my english is bad.
Then, here is my issue:
I try to make an app for iOS with PhoneGap 2.8.1 . Evrything is going well on Android, now I just want to move my code on Xcode to compile on iPad or iPhone.
The probleme I have is with FileTransfer, when I upload an image. The transfer itself has no problem, as it finishes with a response code 200, so it's a success.
Then, my serve is supposed to return back an XML file, handled by the javascript code. The server works fine, because I have absolutly no problem with Android devices.
So, I made a lot of tests, and it appears that the app has a problem with the success callback or the FileTransfer.upload(). When I just put a simple console.log('success') in this callback function, it's fine. But when I try to use the FileUploadResult object, nothing happens.
And the weirdest thing is, that when I press the main button of the iPad or iPhone, in order to close my app, I see all my logs displayed in the debug window, such as console.log("Code = " + r.responseCode);, like in the PhoneGap example. And here, I can finally see that I actually receive the server response, but it's like something blocks it until I close the app.
Here is that part of the code :
function onPhotoDataSuccess(imageURI) {
console.log("---> Image: "+imageURI);
// File Transfer
var options = new FileUploadOptions();
options.fileKey="file";
options.chunkedMode = false;
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI(window.localStorage.getItem("wsURL")), win, fail, options);
// Transfer succeeded
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
// Handle the XML response
}
else {
alert("No response. Please retry");
}
}
// Transfer failed
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
}
Thanks for your help

two way communication between extension and content javascript files

i am trying to accomplish a two way communication request response in my firefox sidebar extension, i have a file named event.js this resides on the content side, i have another file called sidebar.js file which is residing in the xul. I am able to communicate from event.js to sidebar.js file using the dispatchEvent method. my event in turn raises a XMLHttpRequest in sidebar.js file which hits the server and sends back the response. Now, here i am unable to pass the response to the event.js file. I want the response to be accessed in the event.js file. Till now i have achieved only one way communication. Please help me in getting the two way communication.
Code is as follows:
// event.js file
// This event occurs on blur of the text box where i need to save the text into the server
function saveEvent() {
var element = document.getElementById("fetchData");
element.setAttribute("urlPath", "http://localhost:8080/event?Id=12");
element.setAttribute("jsonObj", convertToList);
element.setAttribute("methodType", "POST");
document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("saveEvent", true, true);
element.dispatchEvent(evt);
//Fetching the response over here by adding the listener
document.addEventListener("dispatchedResponse", function (e) { MyExtension.responseListener(e); }, false, true);
}
var MyExtension = {
responseListener: function (evt) {
receivedResponse(evt.target.getAttribute("responseObject"));
}
}
function receivedResponse(event) {
alert('response: ' + event);
}
// sidebar.js file
window.addEventListener("load", function (event) {
var saveAjaxRequest = function (urlPath, jsonObj, methodType, evtTarget) {
var url = urlPath;
var request = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Components.interfaces.nsIXMLHttpRequest);
request.onload = function (aEvent) {
window.alert("Response Text: " + aEvent.target.responseText);
saveResponse = aEvent.target.responseText;
//here i am again trying to dispatch the response i got from the server back to the origin, but unable to pass it...
evtTarget.setAttribute("responseObject", saveResponse);
document.documentElement.appendChild(evtTarget);
var evt = document.createEvent("dispatchedRes"); // Error line "Operation is not supported" code: "9"
evt.initEvent("dispatchedResponse", true, false);
evtTarget.dispatchEvent(evt);
};
request.onerror = function (aEvent) {
window.alert("Error Status: " + aEvent.target.status);
};
//window.alert(methodType + " " + url);
request.open(methodType, url, true);
request.send(jsonObj);
};
this.onLoad = function () {
document.addEventListener("saveEvent", function (e) { MyExtension.saveListener(e); }, false, true);
}
var MyExtension =
{
saveListener: function (evt) {
saveAjaxRequest(evt.target.getAttribute("urlPath"), evt.target.getAttribute("jsonObj"), evt.target.getAttribute("methodType"), evt.originalTarget);
}
};
});
Why are you moving your fetchData element into the sidebar document? You should leave it where it is, otherwise your content code won't be able to receive the event. Also, use the content document to create the event. Finally, document.createEvent() parameter for custom events should be "Events". So the code after your //here i am again trying comment should look like:
evtTarget.setAttribute("responseObject", saveResponse);
var evt = evtTarget.ownerDocument.createEvent("Events");
evt.initEvent("dispatchedResponse", true, false);
evtTarget.dispatchEvent(evt);
Please note however that your code as you show it here is a huge security vulnerability - it allows any website to make any HTTP requests and get the result back, so it essentially disables same-origin policy. At the very least you need to check that the website talking to you is allowed to do it (e.g. it belongs to your server). But even then it stays a security risk because server response could be altered (e.g. by an attacker on a public WLAN) or your server could be hacked - and you would be giving an attacker access to sensitive data (for example he could trigger a request to mail.google.com and if the victim happens to be logged in he will be able to read all email data). So please make this less generic, only allow requests to some websites.

Resources