I'm not the best with Javascript and I seem to have got stuck.
I have a map in place and I need the Lat/Long for a location (that's fine) but the output comes in an alert box. I just need the values themselves.
E.g document.write(latt); document.write(longg);
At the moment this is the code that outputs the box:
function showPointLatLng(point)
{
alert("Latitude: " + point.lat() + "\nLongitude: " + point.lng());
}
Any help would be great, Thanks!
P.S
I think this is the controller:
function usePointFromPostcode(postcode, callbackFunction) {
localSearch.setSearchCompleteCallback(null,
function() {
if (localSearch.results[0])
{
var resultLat = localSearch.results[0].lat;
var resultLng = localSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
callbackFunction(point);
}else{
alert("Postcode not found!");
}
});
localSearch.execute(postcode + ", UK");
}
Looks like you can swap the showPointLatLng call with:
document.write( point.lat() + "," + point.lng() );
As lat/long come from calls to methods of the existing point object.
If you are asking how to make that work...
function showPointLatLng(point) {
document.write("Latitude: " + point.lat() + "\nLongitude: " + point.lng());
}
// Eg, ...
showPointLatLng({
lat : function(){ return 98; }
lng : function(){ return 42; /*the meaning of life!*/ }
});
Instead of document.write you could do something like this:
var info = document.createElement('div');
info.innerHTML = point.lat() + "," + point.lng();
document.body.appendChild(info);
Related
I'm working on trying to trigger an event (to unhide an alert or image) based on gps coordinates falling within a certain range.
I think I need to do something like: If GPS Lat is > x (set based on location I want them to go to) and < y & GPS Long is > z and < a, then show (use js change css to display: block).
Am I down the right path? I'll post what I have as the basics of getting the GPS coordinates to just appear. I'm learning as I go here, so any help is appreciated for the proper structure. Thank you.
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// device APIs are available
//
function onDeviceReady() {
var options = { timeout: 100000 };
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');
}
UPDATE:
I have gotten to the point where I'm not getting errors, now I'm hoping for some help to get a heading based on my current location and the destination. Any help is greatly appreciated. I'm posting my current code below:
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
var gpscoord = null;
var destLat = 37.200401
var destLon = 93.278610
function onDeviceReady() {
var gpsOptions = { timeout: 5000 };
gpscoord = navigator.geolocation.getCurrentPosition(gpsSuccess, gpsError, gpsOptions);
}
//gpsSuccess
//
function gpsSuccess(position) {
var lat = document.getElementById('latitude');
var lon = document.getElementById('longitude');
lat.innerHTML = 'Latitude:' + position.coords.latitude;
lon.innerHTML = 'Longitude:' + position.coords.longitude;
document.getElementById('gotoLat').innerHTML = 'Destination Latitude: ' + destLat;
document.getElementById('gotoLon').innerHTML = 'Destination Longitude: ' + destLon;
}
function gpsError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
<div class="container">
<br/>
<br/>
<p id="latitude">Watching latitude...</p>
<p id="longitude">Watching longitude...</p>
<br/>
<p id="gotoLat">Destination latitude...</p>
<p id="gotoLon">Destination longitude...</p>
</div>
Yeah that looks fine. The watcher will call onSuccess when the GPS has been successfully polled, and returns data.
I would save the Longitude and Latitude in the global scope, and then you can perform what ever kind of logic you want on it.
I was wondering how can I make it posible to get rid of putting "new" before a function, for example:
new functionToDo("thingsToDo").iGotYouBruh("Halo Humans");
is there a posible way of doing this without the "new"?
here is the code I'm trying to use without the "new":
function local (title) {
var storeTitle = title;
this.addL = function(lString) {
var storeText = lString;
localStorage.setItem(storeTitle, storeText);
console.info("Locally stored " + storeTitle.toUpperCase() + " with " + storeText.substring(0, 10) + "... As text.");
};
this.removeL = function() {
localStorage.removeItem(storeTitle);
console.info("Locally removed " + storeTitle + ".");
};
this.getL = function () {
localStorage.getItem(storeTitle);
console.info("Locally got string of " + storeTitle + ": " + localStorage.getItem(storeTitle));
};
};
and here's what I would have to do to invoke the function:
new local("storedElement").getL();
This is possible by checking whether this is an instance of the function itself and returning a new instance otherwise:
function local (title) {
if (!(this instanceof local)) {
return new local(title);
}
var storeTitle = title;
this.addL = function(lString) {
var storeText = lString;
localStorage.setItem(storeTitle, storeText);
console.info("Locally stored " + storeTitle.toUpperCase() + " with " + storeText.substring(0, 10) + "... As text.");
};
this.removeL = function() {
localStorage.removeItem(storeTitle);
console.info("Locally removed " + storeTitle + ".");
};
this.getL = function () {
localStorage.getItem(storeTitle);
console.info("Locally got string of " + storeTitle + ": " + localStorage.getItem(storeTitle));
};
};
You could use JavaScript closures. In particular look at the "Using Closures for the Module Pattern" section of this webpage for a full description. The idea is to have the function return an literal with all the required methods. Any functions or variables that you want to be kept private are just local variables for the function.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a problem with the final values assigned to global variables (success, count_error, error) in my code below. Before the outputting section if I don't include "alert( success );" all values are zero. However if I include that line then the correct values are outputted.
Why is this, is there something wrong with the variable scope ?
<html>
<head>
<script src="../jquery-1.11.0.js"></script>
<script>
var rows_all = [1,2,3,4,5,6,7,8,9,10],
success = 0,
count_error = 0,
error = [];
/////////////////////////////////////////////////////////////////////////
// In test_addresses create lat/lon [number] from coordinates [string] //
/////////////////////////////////////////////////////////////////////////
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT cartodb_id FROM test_addresses" + "&api_key=******", function(data) {
//get #rows for loop function
//$.each(data.rows, function(key, val) {
//rows_all.push(val['cartodb_id']);
//});
//loop through rows (get coordinates), manipulate + post values
$.each(rows_all, function(key1, val1) {
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT address, coordinates FROM test_addresses WHERE cartodb_id=" + val1 + "&api_key=******", function(data1) {
$.each(data1.rows, function(key2, val2) {
address = val2['address'];
lat_lon = val2['coordinates'];
if (lat_lon.indexOf('?') === -1) {
lat = parseFloat( lat_lon.split(',')[0] );
lon = parseFloat( lat_lon.split(',')[1] );
$.post("http://******.cartodb.com/api/v2/sql?q=" + "UPDATE test_addresses SET lat=" + lat + ", lon=" + lon + "WHERE cartodb_id=" + val1 + "&api_key=******");
success++; //number of successfully completed operations
}
else {
count_error++; //#error operations
list = {};
list["id"] = val1; //#which cartodb_id in table
list["address"] = address; //#which matching address in table
error.push(list);
}
});
});
});
alert( success );
//Ouput text
$("#result").html(success + " entries successfully geocoded. </br><br>There were " + count_error + " errors. <br>More pecifically at cartodb_id : address:");
$.each(error, function(key4, val4) {
$("#result").append("<br> " + val4["id"] + " : " + val4["address"]);
});
$.each(rows_all, function(key5, val5) {
$("#result").append("<br>" + key5);
});
});
</script>
</head>
<body>
<p id="result"></p>
</body>
</html>
It is an asynchronous request, so the alert() will fire before getting the data. So you should change the code like,
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT cartodb_id FROM test_addresses" + "&api_key=******", function (data) {
//get #rows for loop function
//$.each(data.rows, function(key, val) {
//rows_all.push(val['cartodb_id']);
//});
//loop through rows (get coordinates), manipulate + post values
$.each(rows_all, function (key1, val1) {
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT address, coordinates FROM test_addresses WHERE cartodb_id=" + val1 + "&api_key=******", function (data1) {
$.each(data1.rows, function (key2, val2) {
address = val2['address'];
lat_lon = val2['coordinates'];
if (lat_lon.indexOf('?') === -1) {
lat = parseFloat(lat_lon.split(',')[0]);
lon = parseFloat(lat_lon.split(',')[1]);
$.post("http://******.cartodb.com/api/v2/sql?q=" + "UPDATE test_addresses SET lat=" + lat + ", lon=" + lon + "WHERE cartodb_id=" + val1 + "&api_key=******");
success++; //number of successfully completed operations
alert(success);
} else {
count_error++; //#error operations
list = {};
list["id"] = val1; //#which cartodb_id in table
list["address"] = address; //#which matching address in table
error.push(list);
}
});
//Ouput text
$("#result").html(success + " entries successfully geocoded. </br><br>There were " + count_error + " errors. <br>More pecifically at cartodb_id : address:");
$.each(error, function (key4, val4) {
$("#result").append("<br> " + val4["id"] + " : " + val4["address"]);
});
$.each(rows_all, function (key5, val5) {
$("#result").append("<br>" + key5);
});
});
});
});
You should put the code inside the scope of $.getJSON itself. So it will run only after getting the data.
Actually its not alert() doing the magic. If you put an alert, the success event will happen with in less timespan, before the user clicks ok button. Within that time all the values will be populated.
I type in scroll(0,10,200,10);
But when it runs it passes the string "xxpos" or "yypos" and I did try it without the appostraphes, but it just didn't work.
scroll = function(xpos,ypos,time,rounds){
var xxpos = xpos*1;
var yypos = ypos*1;
var rrounds = rounds*1;
var ttime = time*1;
x = 0;
xyz=window.setInterval("scroller('xxpos','yypos','ttime','rrounds')",ttime);
}
function scroller(xpos,ypos,time,rounds){
alert(xpos + ypos + time + rounds);
}
Don't use strings, use closures (anonymous functions).
window.setTimeout(function() {
scroller(xxpos, yypos, ttime, rrounds);
}, ttime);
It should be like this:
xyz=window.setInterval("scroller(" + xxpos + "," + yypos + "...
otherwise you just pass strings xxpos, yypos etc.
do you happen to know that in your code, each call to scroll() builds a timer?
do you mean to do it like it was a loop? then:
xyz = window.setTimeout(function(){
scroller(xxpos,yypos,ttime,rrounds)
},ttime);
You should use closure:
...
xyz = window.setInterval(function() { scroller(xxpos,yypos,ttime,rrounds); }, ttime);
...
That's because the string does not become the variable.
This would work:
window.setInterval("scroller("+ xxpos + "," + yypos + "," + ttime + "," + rrounds + ")",ttime);
Or better:
window.setInterval(function() { scroller(xxpos, yypos, ttime, rrounds); }, ttime);
I've written the following code to get JSON data with a POST request.
$.post("http://example.com/songs/search_api/index.php",
"data[Song][keyword]=Stereophonics",
function(data){
/*$("#results").append(data);*/
alert("test");
var songdata = JSON.parse(data);
//$("#results").empty();
var i = 0;
for (i=0;i<=songdata.total;i++)
{
//alert(i);
var songhtml = "<ul><li><img src=\"" + songdata.data[i].artwork + "\" /></li><li>" + songdata.data[i].title + "</li><li>" + songdata.data[i].artist + "</li><li>" + songdata.data[i].length + "</li><li>" + songdata.data[i].listen + "</li></ul>";
//alert(songhtml);
$("#results").append(songhtml);
}
//var objectasstring = concatObject(songdata);
//alert(objectasstring + "\n\n" + songdata);
}
);
The problem is as soon as I put in a function (this works without the above code) the function fails to run;
function postRequest() {
alert("hello??");
}
This is for mobile Safari on the iPhone.
Thanks in advance.
Solved! My problem? The form. I was using a form so the page was being refreshed when the function was run.