I am trying to build a simple mobile app that checks database and gives user the correct venue based on their location. Essentially, I have two files: one with geolocation, JavaScript and AJAX call, and another one with php that checks the database and sends the correct result back. Everything on its own is working perfectly fine, but when I try to send geolocation coordinates to PHP it returns undefined. Why does it not pick up the coordinates (they pop up in a separate window)? How can I fix it?
Here is my geolocation and AJAX code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {
var latitude;
var longitude;
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
var request = $.ajax({
url: "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php?latitude=" + latitude + "&longitude=" + longitude,
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#ajax").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
</script>
And here is the bit of PHP that handles these variables:
if (isset($_GET['latitude']) && isset($_GET['longitude'])) {
$latitude = $_GET['latitude'];
$longitude = $_GET['longitude'];
echo "Geolocation seems to work...";
echo $latitude;
echo $longitude;
//continue here
}else{
echo "Hello. I am your geolocation and I am not working.";
}
What I get is "Geolocation seems to work...undefinedundefined"
The Geolocation API is asynchronous, so you have to wait for the result to return
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
url : "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php",
data : {latitude : latitude, longitude : longitude},
type : "GET",
dataType : "html"
}).done(function(msg) {
$("#ajax").html(msg);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}
remove var in both variable. Those two are not visible outside displayPosition. When you use the $.ajax call you're using latitude and longitude declared right under the $(document).raedy() but you never assign nothing to them so they're undefined.
Hope this solve your issue.
P.S. You se the values in the alert because you're using ones from position, not from your variables.
Do not use var inside your displayPosition function. You do not want to declare new variables inside the scope of the function, you want to assign values to the existing variables you declared in the global scope earlier.
Related
I'm Trying to build an app with Cordova. With the app you should take pictures, these pictures needs to be uploaded to a database together with the location where the picture is taken.
The app on default shows a x number of the most nearest taken pictures to your live location.
Beneath here i post the javascript code i have right now, most of the code is from Cordova self. Is it better to modify this code or start over?
I can now access the camera and take a picture, but how do i upload this picture together with the location to a database?
And how can load the nearest pictures from the database?
var Latitude = undefined;
var Longitude = undefined;
window.onload = function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady(){
navigator.notification.alert("ready");
document.getElementById("camera").addEventListener
("click", cameraTakePicture);
}
function cameraTakePicture() {
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData, imageURI) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
getLocation();
navigator.notification.alert(image.src);
}
function onFail(message) {
alert('Failed because: ' + message);
}
}
function getLocation() {
navigator.notification.alert("start locatie");
navigator.geolocation.getCurrentPosition(onPicturesSuccess, onPicturesError, { enableHighAccuracy: true });
}
var onPicturesSuccess = function (position) {
Latitude = position.coords.latitude;
Longitude = position.coords.longitude;
getPictures(Latitude, Longitude);
}
function getPictures(latitude, longitude) {
//Load pictures which are the nearest
}
var onPicturesWatchSuccess = function (position) {
var updatedLatitude = position.coords.latitude;
var updatedLongitude = position.coords.longitude;
if (updatedLatitude != Latitude && updatedLongitude != Longitude) {
Latitude = updatedLatitude;
Longitude = updatedLongitude;
getPictures(updatedLatitude, updatedLongitude);
}
}
// Error callback
function onPicturesError(error) {
console.log('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Watch your changing position
function watchPicturePosition() {
return navigator.geolocation.watchPosition
(onPicturesWatchSuccess, onPicturesError, { enableHighAccuracy: true });
}
You can use Cordova File Transfer Plugin to upload your photos to your backend service (DB). In FT Plugin you can add some additional headers, or properties e.g. LAT and LON properties.
Since you didn't specifically mention it, I'm going to assume you have access to jQuery inside your Cordova app.
Inside your onSuccess you have to make an AJAX call that submits the image and location to your PHP server. Below is an example:
var request = {
'url': 'path/to/your/php/script.php',
'method': 'POST',
'data': {
'image': image.src,
'location': getLocation()
}
}
$.ajax(request).done(function(response) {
// request is done
});
Your PHP server script will have to take the incoming data and save it to your database.
I am experimenting using in using $.ajax to use geolocation to input weather data into a page from Wunderground. I am able to successfully input weather data into my page when I manually enter my location into code using plain vanilla JS but want to take it a step further. I am running the following code and get an alert box asking for location but after clicking okay see no code updates to my HTML. When opening the console in dev tools I do not see any error messages.
var Geo={};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successGeo,error);
}
else {
alert('Geolocation is not supported');
}
function error() {
alert("Cant find you");
}
function successGeo(position) {
Geo.lat = position.coords.latitude;
Geo.lng = position.coords.longitude;
}
function showPosition(position) {
var geoLat = position.coords.latitude;
var geoLong = position.coords.longitude;
var key = "8704dded63fc077d";
var ForecastURL = "http://api.wunderground.com/api/"; + key + "/forecast/q/" + geoLat + "," + geoLong + ".json";
var WeatherURL = "http://api.wunderground.com/api/"; + key + "/conditions/q/" + geoLat + "," + geoLong + ".json";
$.ajax({
url : WeatherURL,
dataType : "jsonp",
success : function(parsed_json) {
var temp_f = parsed_json['current_observation']['temp_f'];
document.getElementById("currentTemp").innerHTML = temp_f;
}
});
$.ajax({
url : ForecastURL,
dataType : "jsonp",
success : function(parsed_json) {
var fore_high = parsed_json['forecast']['simpleforecast']['forecastday'][0]['high']['fahrenheit'];
var fore_low = parsed_json['forecast']['simpleforecast']['forecastday'][0]['low']['fahrenheit'];
document.getElementById("high1").innerHTML = fore_high;
document.getElementById("low1").innerHTML = fore_low;
}
});
} //ends showposition function
I have some div elements set up in the footer of index.html just so I can confirm the elements are being updated. I'll worry more about style and alignment later.
<footer> <!--//contains ajax weather data-->
<div id="high1"></div>
<div id="current_temp"></div>
<div id="low1"></div>
</footer>
I'm pretty stumped as to why I can't get a response, especially since I'm not picking up any errors in the console.
I am trying to fetch the current location using the geolocation . A month before it was giving correct location but not am getting different location . I have used the same code as below.
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
/*x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
*/ var query = "?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
var stateObj = { query: query };
history.pushState(stateObj, "query added", query);
var flag = true;
/*var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
req.onreadystatechange=function(){if((r.readyState==4)&&(r.status==200)){ console.log('location was sended to server'); }};
req.open("GET","?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude,true);
req.send(null);
*/
}
Another problem is its fetching the latlong based on isp not on IP. So if i use this code using mobile internet ! It gives latlong of another state. Is there any way to make this work again?
I am working on a Google Map which needs to show:
a KML (floor-plan)
a Polyline which should take its coordinates from a GET response, each 5 seconds.
I would like the polyline to update itself with the new coordinates that arrives from the RESTful API.
This is the code [updated]:
var FlightPath1 = []
$(document).ready(function() {
var BASE_URL = "https://its.navizon.com/api/v1/sites/" //Do not change this
SITE_ID = "1001" // Your site ID here
MAC_add = "00:1E:8F:92:D0:56" //Mac address of the device to track
USERNAME = "demo#navizon.com" // Your username
PASSWORD = "" // Your password
var Path1=new google.maps.Polyline({
path:FlightPath1,
strokeColor:"#F020FF",
strokeOpacity:0.8,
strokeWeight:2
});
// Send the request
jQuery.support.cors = true; // Enable cross-site scripting
function makeCall() {
$.ajax({
type: "GET",
url: BASE_URL + SITE_ID + "/stations/" + MAC_add + "/",
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
},
success: function(jimmi) {
// Output the results
if (typeof jimmi === "string") {
jimmi = JSON.parse(jimmi);
}
//Display the results
FlightPath1.push("new google.maps.LatLng(" + jimmi.loc.lat + "," + jimmi.loc.lng + "),");
var mapOptions = {
zoom: 19,
center: new google.maps.LatLng(jimmi.loc.lat,jimmi.loc.lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var SanDiegoKML = new google.maps.KmlLayer({
url: 'https://s3.amazonaws.com/navizon.its.fp/1001/05w0kyw829_a.kml'
});
SanDiegoKML.setMap(map);
google.maps.event.addDomListener(window, 'load', jimmi);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
window.setTimeout(makeCall, 5000); //run the script each 5000 milliseconds
}
makeCall();
})
But I nothing happens. And I get no errors neither.
Could some one help me?
Thanks..
Two issues:
The necessary var, Path1 is internal and private to initialize(), therefore out of scope with regard to the ajax success function which is in an entirely different scope.
The ajax success function does nothing other than to push a string derived from the response onto an array. Doing so will not, in itself, affect the polyline.
Fix (1) first, then (2).
Currently working on a weather web-app for iOS. I'm trying to get the coordinates of the user and put the latitude and longitude in my Ajax request (on the api Wunderground) .
Here's my code (EDIT):
<script type="text/javascript">
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(getLocation, unknownLocation);
function getLocation(pos)
{
var lat = pos.coords.latitude;
var lon = pos.coords.longitude;
$.ajax({
url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+ lat +","+ lon +".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}
function unknownLocation()
{
alert('Could not find location');
}
});
</script>
As you can see I "simply" have to create 2 vars lat and lon and add them in my request. I tried a lot of variants but I can't get this code working.
Any idea of what I'm doing wrong ?
Thank you very much !
Your variable declarations are in the middle of the .ajax call, and are making the JavaScript structure invalid. Also, I'm not sure why you're using "function($)", normally with jQuery the $ is reserved and shouldn't be used as a function parameter.
<script type="text/javascript">
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(onPositionUpdate);
});
function onPositionUpdate(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
$.ajax({
url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+lat+","+lon+".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}
</script>