I'm trying to get Firefox 13 to turn a geolocation position object into a JSON string, but it's returning an empty string rather than the correct string representation of my JSON object. This is working fine in the latest versions of Chrome and Safari, as well as the Android browser. Here's my code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
//Success handler
console.log(position); //This outputs the position object to the console
var gps = JSON.stringify(position);
console.log(gps); //This outputs an empty string!
},
function (error)
{
//Handle error
},
{ maximumAge: 3000, timeout: 60000, enableHighAccuracy: true }
);
}
else {
//Handle error
}
In Chrome, this outputs a geolocation object, and this string:
"{"coords":{"latitude":XYZ,"heading":null,"accuracy":40,"altitudeAccuracy":null,"altitude":null,"longitude":XYZ,"speed":null},"timestamp":1339712284200}"
However, in Firefox 13 the output is just an empty string, even though the geolocation object that's printed to the console is to all intents and purposes the same as the object displayed by Chrome. Any ideas on what's going wrong here? This seems to be a related issue, but I don't see a solution there either. IE9 displays the same behaviour, by the way.
I created a clone function to clone the Geolocation position (or any other) object into an object that will be stringified as expected:
function cloneAsObject(obj) {
if (obj === null || !(obj instanceof Object)) {
return obj;
}
var temp = (obj instanceof Array) ? [] : {};
// ReSharper disable once MissingHasOwnPropertyInForeach
for (var key in obj) {
temp[key] = cloneAsObject(obj[key]);
}
return temp;
}
Note: May not support types not used in Geoposition type (eg Date)
You would then use it as follows in your code:
var gps = JSON.stringify(cloneAsObject(position));
Hope this helps someone :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With