Hi I try to get the geolocation of the user using cordova. The longitude and latitude should be get in php and cookies should be created with these values. But when I start the application on my device a blank white screen become show. How can I get the javascript variables with php right?
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
//
function onSuccess(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
window.location.href = "http://".$_SERVER['HTTP_HOST']."/loc/www/login.php?latitude=" + latitude;
window.location.href = "http://".$_SERVER['HTTP_HOST']."/loc/www/login.php?longitude=" + longitude;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
<?php
$latitude = $_GET["latitude"];
$longitude = $_GET["longitude"];
$t = time() + 60 * 60 * 24 * 1000;
setcookie("latitude", $latitude, $t);
setcookie("longitude", $longitude, $t);
?>
You have PHP variable combined with javascript, please fix to this:
window.location.href = "http://<?php echo $_SERVER['HTTP_HOST'] ?>/loc/www/login.php?latitude=" + latitude;
You change the location previously and then you try to change again, this will not work:
window.location.href = "http://<?php echo $_SERVER['HTTP_HOST'] ?>/loc/www/login.php?longitude=" + longitude;
Why you don't try to create a API to be consumed by your cordova App, send the location to the webservice when cordova is ready?, you could send both values, latitude and longitude to the server and locally keep those values.
Related
My HTML script gathers the latitude & longitude and sends them to another PHP script via ajax, which inserts those values into mysql, problem is that AJAX inserts NULL values into the table. It's inserting values of "0.000000" for both Latitude & Longitude, lat & long are type float(10,6) in the DB as stated by the internet for best practice with gps coords. I'm obvious new developer please help -- HTML Script
<!DOCTYPE html>
<html>
<head>
<title>AJAX DATABASE</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
/*/ Wait for Cordova to load
/*/
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// Cordova is ready
//
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = {enableHighAccuracy:true, timeout: 3000, maximumAge:0};
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var latitude = document.getElementById("lat");
latitude.innerHTML = position.coords.latitude;
var longitude = document.getElementById("longitude");
latitude.innerHTML = position.coords.latitude;
insertDB(position.coords.latitude,position.coords.latitude);
}
// onError Callback receives a [PositionError](PositionError/positionError.html) object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Options: throw an error if no update is received every 30 seconds.
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });
// Sends latitude & longitude value to php script and alerts on success
function insertDB(latitude, longitude){
var xttp = new XMLHttpRequest();
xttp.onreadystatechange = function(){
if(this.readyState == 4){
document.getElementById('longitude').innerHTML =
this.responseText;
alert("state changed by ajax")
}
}
xttp.open("GET", "ConnectTest.php?
latitude="+latitude+"&longitude="+longitude, true);
xttp.send();
}
</script>
</head>
<body>
<p id="lat"></p><br>
<p id="longitude"></p>
</body>
</html>
and the PHP --
<?php
//POST VARIABLES
$one = $_GET['latitude'];
$two = $_GET['longitude'];
//ESTABLISH CONNECTION
$servername = "localhost:3306";
$user = "client";
$pass = "sonic_client";
$db_name = "sonicstrains";
$server = mysqli_connect($servername, $user, $pass, $db_name);
$sql = "SELECT * FROM 'users' WHERE 'latitude' = ".$two;
$result = mysqli_query($server, $sql);
if(!isset($_GET['latitude'])){
echo "Nothing is set";
}
if(!$server){
die("Connetion error".mysqli_connect_error());
}else{
if (!$result){
$insert = "INSERT INTO users (latitude, longitude) VALUES ('$one', '$two')";
mysqli_query($server, $insert);
echo "Coordinates Inserted";
}
}
?>
Replace the xttp open and send functions with below:
xttp.open("POST", "ConnectTest.php, true);
xttp.send(latitude="+latitude+"&longitude="+longitude);
I am new to jQuery and PHP. This might be a trivial question or not.
Normally jQuery handles form input, post it to PHP, and then let PHP passes it to a database.
In my case, I have the current user's geographic location and I compare the user's geographic location against the destination's geographic location in JavaScript. If those two locations are close which means the user is arrived at the destination, record in the database by inserting the destination's Identifier (let's just say Id =1 to keep it simple) for the current user under the Place_Id filed in database. The table in the database only has two columns (userId and placeId).
I wonder how to achieve by jQuery and PHP.
Here is the JavaScript code for geographic locations comparison.
I need help on the function postIt() to initiate PHP using jQuery and the associate PHP.
<script type="text/javascript" ,
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
var lat;
var long;
window.onload=function(){
getLocation();
}
function getLocation() {
if (navigator.geolocation) {
watchId = navigator.geolocation.watchPosition(showPosition, locationError,
{maximumAge:0, timeout:10000, enableHighAccuracy:true});
}
else {
alert("Browser doesn't support Geolocation. Visit http://caniuse.com to
discover browser support for the Geolocation API.");
}
}
function locationError(error) {} // error function here
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
lat = position.coords.latitude;
long = position.coords.longitude;
comparePosition();
}
function comparePosition()
{
var userCurrentLat = lat;
var userCurrentLong = long;
var Dest1_Lat = 38.00; //this is just for demo
var Dest1_Long = -72.00; //this is just for demo
if (userCurrentLat == Dest1_Lat
&& userCurrentLong == Dest1_Long)//just a simplified way of comparison
{
postIt();
}}
function postIt()
{ $.post ('insertDest1.php', {current_user_id, //pseudo jQuery code here
destinationId(1)}, callback function() ) //where I need help
}
</script>
PHP (insertDest1.php)
<?php
include ('mysqli_connect.php');
$query = "INSERT INTO user (userId,placeId) VALUES
('current_user_id' , '1')";
$result = #mysqli_query ($dbc, $query); // Run the query.
if ($result) { // If it ran OK.
// Print a message.
echo '<h1 id="mainhead">Success!</h1>';
}
else { // If it did not run OK.
echo '<h1 id="mainhead">Error</h1>';
}
?>
Use $.ajax for more configuration options:
function postIt()
{
$.ajax({
url: 'insertDest1.php',
type: 'POST',
data:{
userId: 'current_user_id', // replace with actual user id
placeId: 'the_place_id' // replace with actual place id
},
success: function(serverResponse) {
// handle output from server here ('Success!' or 'Error' from PHP script)
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// handle any network/server errors here
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
}
});
}
Setup PHP file to handle POST data from AJAX
<?php
include ('mysqli_connect.php');
# Always sanitize input from $_POST variable to prevent SQL injection
$userId = $dbc->escape_string($_POST['userId']); // current_user_id
$placeId = $dbc->escape_string($_POST['placeId']); // the_place_id
$query = "INSERT INTO user (userId, placeId) VALUES ('".$userId."' , '".$placeId."')";
$result = #mysqli_query ($dbc, $query); // Run the query.
if ($result) { // If it ran OK.
// Print a message.
echo '<h1 id="mainhead">Success!</h1>';
}
else { // If it did not run OK.
// Print error.
echo '<h1 id="mainhead">Error</h1>';
}
?>
I'm developing a mobile web application with Spring MVC. For geolocation, I get the code from here
I ran the demo from my phone on that site and it's asking for location permission, same thing on jsfiddle demo, and it's working. If I don't have Gps enable I get '"Unable to retrieve your location'.
But on my application, I get instantly the above message, without asking for permission(also, removed all blocked apps from chrome).
On PC, geolocation is working,through my app, but on my phone, not.. What can be the problem?Meaning.. why geolocation is not working on my phone through my app, but it's working for other sites. On my phone, goes directly to error() function.
Maybe I have to make some changes in the configuration files,or I don't know..
LE: Tested on 2 more devices, same output:Unable to retrieve your location ... (GPS enabled)
LE2:I checked the error code. I'm getting permission denied
This is the Fiddle
<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>
//Javascript
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
};
function error() {
output.innerHTML = "Unable to retrieve your location";
};
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
You can check this code,
https://github.com/makubex88/MobileHTML5CodeCamp/blob/master/mobilehtml5.html
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML = "<img src='" + img_url + "'>";
}
I have an MVC4 Web API application where i have my Api Controller and Code-First EF5 database and some JavaScript functions for the functionality of my app including my Ajax Calls for my Web Api Service.I did the project on MVC because i was having trouble installing Cordova in VS2012, so i have decided to use Eclipse/Android Phonegap platform.Is there a way where i can call my web api service and be able to retrieve my database data designed EF5(MVC4) in my Android Phonegap application without having to start from the beginning the same thing again.I know phonegap is basically Html(JavaScript and Css) but i am having trouble calling my service using the same HTML markup that i used MVC4.I am a beginner please let me know if what i am doing is possible and if not please do show me the light of how i can go about this. T*his is my Html code*
<script type="text/javascript" charset="utf-8" src="phonegap-2.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="barcodescanner.js"></script>
<script type="text/javascript" language="javascript" src="http://api.afrigis.co.za/loadjsapi/?key=...&version=2.6">
</script>
<script type="text/javascript" language="javascript">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
//initialize watchID Variable
var watchID = null;
// device APIs are available
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = { timeout: 30000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
//declare a global map object
var agmap = null;
// declare zoom control of map
var zoomCtrl = null;
function initAGMap() {
agmap = new AGMap(document.getElementById("MapPanel"));
//TODO: must retrieve coords by device location not hard corded.
agmap.centreAndScale(new AGCoord(-25.7482681540537, 28.225935184269), 5); // zoom level 5 heres
// making zoom controls for map
var ctrlPos = new AGControlPosition(new AGPoint(10, 10), AGAnchor.TOP_LEFT);
zoomCtrl = new AGZoomControl(1);
agmap.addControl(zoomCtrl, ctrlPos);
}
function removeZoomCtrl()
{
zoomCtrl.remove();
}
//function search() {
// var lat = $('#latitude').val();
// var long = $('#longitude').val();
// $.ajax({
// url: "api/Attractions/?longitude=" + long + "&latitude=" + lat,
// type: "GET",
// success: function (data) {
// if (data == null) {
// $('#attractionName').html("No attractions to search");
// }
// else {
// $('#attractionName').html("You should visit " + data.Name);
// displayMap(data.Location.Geography.WellKnownText, data.Name);
// }
// }
// });
//}
//function GetCoordinate() {
//todo: get details from cordova, currently mocking up results
//return { latitude: -25.5, longitude: 28.5 };
}
function ShowCoordinate(coords) {
agmap.centreAndScale(new AGCoord(coords.latitude, coords.longitude), 5); // zoom level 5 here
var coord = new AGCoord(coords.latitude, coords.longitude);
var oMarker = new AGMarker(coord);
agmap.addOverlay(oMarker);
oMarker.show();
//todo: create a list of places found and display with marker on AfriGIS Map.
}
function ScanProduct()
{
//todo retrieve id from cordova as mockup
//This is mockup barcode
//return "1234";
//sample code using cordova barcodescanner plugin
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
//Callback function if barcodedont exist
function (error) {
alert("Scanning failed: " + error);
});
}
//Function to display Success or error in encoding.
function encode(type, data) {
window.plugins.barcodeScanner.encode(type, data, function(result) {
alert("encode success: " + result);
}, function(error) {
alert("encoding failed: " + error);
});}
function GetProductDetails(barcodeId,coords)
{
//Ajax Call to my web Api service
$.getJSON("api/products/?barcodeId=" + barcodeId + "&latitude=" + coords.latitude + "&longitude=" + coords.longitude)
.done(function (data) {
$('#result').append(data.message)
console.log(data)
var list = $("#result").append('<ul></ul>').find('ul');
$.each(data.results, function (i, item)
{
if (data.results == null) {
$('#result').append(data.message)
}
else {
list.append('<li>ShopName :' + item.retailerName + '</li>');
list.append('<li>Name : ' + item.productName + '</li>');
list.append('<li>Rand :' + item.price + '</li>');
list.append('<li>Distance in Km :' + item.Distance + '</li>');
//Another Solution
//var ul = $("<ul></ul>")
//ul.append("<li> Rand" + data.results.productName + "</li>");
//ul.append("<li> Rand" + data.results.Retailer.Name + "</li>");
//ul.append("<li> Rand" + data.results.price + "</li>");
//ul.append("<li> Rand" + data.results.Distance + "</li>");
//$("#result").append(ul);
}
});
$("#result").append(ul);
});
}
function ShowProductDetails()
{
//todo: display product details
//return productdetails.barcodeId + productdetails.retailerName + ': R' + productdetails.Price + productdetails.Distance;
}
//loading javascript api
$(function () {
initAGMap();
var coord = GetCoordinate();
ShowCoordinate(coord);
var barcodeId = ScanProduct();
var productdetails = GetProductDetails(barcodeId, coord);
ShowProductDetails(productdetails);
});
</script>
It looks like you're on the right track. The obvious error right now is that it's using a relative URL (api/products/?barcodeId=) to call the Web API. Because the HTML is no longer hosted on the same server as the Web API (even though you might be running them both on your local machine still), this won't work anymore. You need to call the service with an absolute URL (for example, http://localhost:8888/api/products/?barcodeId=).
Where is your Web API hosted right now and how are you running the Cordova code? If the Web API is up and running on your local machine and your Cordova app is running on an emulator on the same machine, you should be able to call the service by supplying its full localhost path.
If it still doesn't work, you'll need to somehow debug the code and see what the errors are.
i have found a script for geolocation resolve with google
in this code there is a key that is 86 char long
i have opened a google api key for the gmail of the website
it is a short key (only 39 chars)
i then changed the key and run the code.
i get the resolve country location that i need.
i then tried from another ip location (at home) and one with a proxy sever and didn't get any thing
i'm not sure if the api key i'm using is set for public or not- how do i check that?
do i have to pay for using it or can be used only with the free 25,000 request per day?
the code i have tried is:
<script type="text/javascript" src="http://www.google.com/jsapi?key="></script>
<script type="text/javascript">
function geoTest() {
if (google.loader.ClientLocation) {
var latitude = google.loader.ClientLocation.latitude;
var longitude = google.loader.ClientLocation.longitude;
var city = google.loader.ClientLocation.address.city;
var country = google.loader.ClientLocation.address.country;
var country_code = google.loader.ClientLocation.address.country_code;
var region = google.loader.ClientLocation.address.region;
var text = 'Your Location<br /><br />Latitude: ' + latitude + '<br />Longitude: ' + longitude + '<br />City: ' + city + '<br />Country: ' + country + '<br />Country Code: ' + country_code + '<br />Region: ' + region;
} else {
var text = 'Google was not able to detect your location';
}
document.write(text);
}
geoTest();
</script>
Seems like the geolocation is not reliable
See Philippe's answer here Is google.loader.clientlocation still supported