I have a script that allows the user to view locations of comms cabinets. I am trying to get html5 to pass latitude and longitude to a php script(geo.php) to update the record in the database with the map coordinates, but keep getting errors:
ReferenceError: Can't find variable: pos
this is my code. Please help me get the latitude and longitude to appear in the link to be called by ajax:
function getLocation() {
navigator.geolocation.getCurrentPosition(function(pos)
{
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
});
}
function saveLocation(building, commNo) {
getLocation();
var latitude = lat;
var longitude = lng;
alert(latitude + longitude);
document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">';
var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
getMap(exchangeName, PCP);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
The geolocation API is asynchronous, just like your ajax call, so you have to wait for the results to return, and even if you did have to wait for the async call, variables are only available inside the scope where they are defined.
function getLocation(callback) {
navigator.geolocation.getCurrentPosition(function (pos) {
callback(pos.coords.latitude, pos.coords.longitude);
});
}
function saveLocation(building, commNo) {
getLocation(function(latitude, longitude) {
document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">';
var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
getMap(exchangeName, PCP);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
});
}
Related
I'm trying to create a weather app, sending Ajax requests to OpenWeatherMap. I've got an error in w.getWeatherFunc, when I'm giving the function sendRequest the parameter of w.weather and then giving the same parameter to the function displayFunc, which I'm calling next.
Here is what I've got in the console:
Uncaught TypeError: Cannot read property 'weather' of undefined
at displayFunc (weather.js:46)
at weather.js:78
How can I fix this and make it work?
function Weather () {
var w = this;
var weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?';
var appid = '&appid=c0a7816b2acba9dbfb70977a1e537369';
var googleUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
var googleKey = '&key=AIzaSyBHBjF5lDpw2tSXVJ6A1ra-RKT90ek5bvQ';
w.demo = document.getElementById('demo');
w.place = document.getElementById('place');
w.description = document.getElementById('description');
w.temp = document.getElementById('temp');
w.humidity = document.getElementById('humidity');
w.getWeather = document.getElementById('getWeather');
w.addCityBtn = document.getElementById('addCity');
w.rmCityBtn = document.getElementById('rmCity');
w.icon = document.getElementById('icon');
w.wind = document.getElementById('wind');
w.time = document.getElementById('time');
w.lat = null;
w.lon = null;
w.cityArray = [];
w.weather = null;
function sendRequest (url, data) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.send();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
data = JSON.parse(request.responseText);
console.log(data);
return data;
} else {
console.log(request.status + ': ' + request.statusText);
}
}
}
function displayFunc (obj) {
console.log('obj ' + obj);
w.icon.src = 'http://openweathermap.org/img/w/' + obj.weather[0].icon + '.png';
var timeNow = new Date();
var hours = timeNow.getHours();
var minutes = timeNow.getMinutes() < 10 ? '0' + timeNow.getMinutes() : timeNow.getMinutes();
w.time.innerHTML = hours + ':' + minutes;
w.place.innerHTML = 'Place: ' + obj.name;
w.description.innerHTML = "Weather: " + obj.weather[0].description;
w.temp.innerHTML = "Temperature: " + w.convertToCels(obj.main.temp) + "°C";
w.humidity.innerHTML = "Humidity: " + obj.main.humidity + '%';
w.wind.innerHTML = 'Wind: ' + obj.wind.speed + ' meter/sec';
}
w.convertToCels = function(temp) {
var tempC = Math.round(temp - 273.15);
return tempC;
}
w.getWeatherFunc = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(location){
w.lat = location.coords.latitude;
w.lon = location.coords.longitude;
var url = weatherUrl + 'lat=' + w.lat + '&lon=' + w.lon + appid;
var result = sendRequest(url, w.weather);
console.log(result);
displayFunc(result);
});
} else {
alert('Browser could not find your current location');
}
}
w.addCityBtn.onclick = function() {
var newCity = prompt('Please insert city', 'Kiev');
var gUrl = googleUrl + newCity + googleKey;
var newCityWeather = null;
sendRequest(url, newCityWeather);
var location = newCityWeather.results[0].geometry.location;
var newUrl = weatherUrl + 'lat=' + location.lat + '&lon=' + location.lng + appid;
sendRequest(newUrl, w.weather);
displayFunc(newCity);
w.cityArray.push(newCity);
}
window.onload = w.getWeatherFunc;
setInterval(function() {
w.getWeatherFunc();
}, 900000);
}
Your ajax return returns into the browsers engine. As its async you need to create a callback:
function sendRequest(url,data,callback){
//if the data was received
callback(data);
}
Use like this
sendRequest("yoururl",data,function(data){
displayFunc(data);
});
The first time you pass the obj to the function it will save it one scope higher. after that, if you don;t pass the object the one you saved earlier will be used.
var objBkp;
function displayFunc (obj) {
if(undefined === obj) obj = objBkp;
else objBkp = obj;
// rest of code here
}
In your sendRequest you are passing only the value of w.weather, not its reference. JavaScript doesn't pass variables by value or by reference, but by sharing. So if you want to give the value to your variable you should do this inside your function sendRequest:
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
w.weather = JSON.parse(request.responseText);
console.log(data);
return data;
} else {
console.log(request.status + ': ' + request.statusText);
}
}
Also, if you are using the attributes, you don't have to pass them in the function as arguments. Besides that fact, it would be good if you also create get() and set()
What does the console.log(result); in getWeatherFunc gives you?
The problem as I see it is that in the displayFunc the parameter passed is undefined.
<script type="text/javascript">
var GOOGLE_API_KEY = "mykey";
var lat, lng;
var geocoder;
var geoCodingUrl;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var geoCodingUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&key=" + GOOGLE_API_KEY;
console.log(geoCodingUrl);
var address = result.address_components[4].longname;
if (address == "Mumbai, India") {
window.location = "url";
}
if(address == "Bangalore, India"){
window.location = "url";
}
if(address == "Jaipur, India") {
window.location = "url";
}
else{
window.location = "url";
}
}
function errorFunction() {
alert ("Geocoder failed");
}
</script>
As per the Google Maps API docs, the geoCodingUrl should return a JSON array. How do I retrieve the city name from that array? The console gives an error that says result variable not found, how do I refer to the array that is returned?
Assuming ur using jquery here is the code
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var geoCodingUrl = "https://maps.googleapis.com/maps/api/geocode/json? latlng=" + lat + "," + lng + "&key=" + GOOGLE_API_KEY;
$.ajax({
url:geoCodingUrl,
method:"GET",
success:function(res){
var result=res.results;
var address = result[0].address_components[4].longname;
if (address == "Mumbai, India") {
window.location = "url";
}
if(address == "Bangalore, India"){
window.location = "url";
}
if(address == "Jaipur, India") {
window.location = "url";
}
else{
window.location = "url";
}
}
})
}
I am working on a geolocation feature that redirects users to pages for their respective cities. I have used Google Maps API and HTML5 Geolocation to try and implement this. On running the below script, address is shown to be an object in the console. However, when I try to make the comparison on the subsequent line, I get an error saying Undefined is not an object(evaluating 'address.results'. How can I make the code work?
<script type="text/javascript">
var GOOGLE_API_KEY = "mykey";
var lat, lng;
var geocoder;
var geoCodingUrl;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var geoCodingUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&key=" + GOOGLE_API_KEY;
console.log(geoCodingUrl);
var address = $.get(geoCodingUrl);
console.log(address);
if (address.results[0].formatted_address[4] == "Mumbai, Maharashtra, India") {
window.location = "url";
}
if(address.results.long_name == "Bangalore, India"){
window.location = "url";
}
if(address.results.long_name == "Jaipur, India") {
window.location = "url";
}
}
function errorFunction() {
alert ("Geocoder failed");
}
</script>
try this
$.get({url:geoCodingUrl,success:function(response){
var address=response.results;
if (address[0].formatted_address[4] == "Mumbai, Maharashtra, India") {
window.location = "url";
}
if(address[0].long_name == "Bangalore, India"){
window.location = "url";
}
if(address[0].long_name == "Jaipur, India") {
window.location = "url";
}
}
})
In index.html under body tag:
+ -
and under <head><script type="text/javascript">:
var url = "get.php";
function ajaxRequest()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var jsondata = eval("(" + xmlhttp.responseText + ")"); //retrieve result as an JavaScript object
document.getElementById("y").innerHTML = jsondata.y;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function setTempInc()
{
var oldUrl = url;
url = url + "9001" + jsondata.y;
ajaxRequest();
url = oldUrl;
}
I don't understand where the problem is. url is a string and jsondata.y is a int but the script doesn't work!
This function does, though:
function setMode(val)
{
var oldUrl = url;
url = url + "91" + val + "000";
ajaxRequest();
url = oldUrl;
}
I would think that
var jsondata = eval("(" + xmlhttp.responseText + ")");
is not available to be called at
url = url + "9001" + jsondata.y;
as it is only defined inside the ajaxRequest function's scope.
Set variables outside functions, to use as a global variable!
This probably will work:
(function() {
var url = "get.php";
var oldUrl = '';
var jsondata = '';
function ajaxRequest()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
jsondata = eval("("+xmlhttp.responseText+")"); //retrieve result as an JavaScript object
document.getElementById("y").innerHTML = jsondata.y;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function setTempInc()
{
oldUrl = url;
url = url + "9001" + jsondata.y;
ajaxRequest();
url = oldUrl;
}
})();
Added Closure to avoid common security problems
I'm using the following code to make a call to a REST API using JavaScript. This code works fine with IE but hangs at send method with Firefox 9.0.1. I believe IE is not cashing the previous response.
I have tried debugging with Firebug, but it's not helping. XMLHttpRequest object, which is for Firefox, is created successfully and it goes through all the code, but no response.
<script language="javascript" type="text/javascript">
function processRequest() {
var signedURI = "http://api.saaspose.com/v1.0/storage/disc?appSID=myappSID&signature=mySignature";
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
if (typeof xmlhttp.overrideMimeType != 'undefined') {
xmlhttp.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Not supported!');
}
xmlhttp.open('GET', signedURI, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
} else {
//alert("ready state : " + xmlhttp.readyState.toString() + " status : " + xmlhttp.status.toString());
}
};
xmlhttp.send(null);
}
</script>
Any idea why is this issue occurring with Firefox but not with IE?
The team had to resolve this issue by adding JSONP support to the WCF services and then using the jQuery at the client end like this:
$(function () {
$("#disc").click(function () {
$.getJSON("http://api.saaspose.com/v1.0/storage/disc?appSID=appsid&signature=signature&callback=?", function (data) {
var items = [];
$("#discResult").append('<br/><b>Status: ' + data.Status + '</b>');
if (data.Status = 'OK') {
var discUsage = data.DiscUsage;
$.each(discUsage, function (key, val) {
items.push('<li id="' + key + '">' + key + ': ' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('#discResult');
}
});
});
});
Thank you all for your comments.