I thought I understood how the default operand worked in JavaScript, but clearly not. I’m trying to first determine the user’s geographic position, and load a map centered on those coordinates. If the device is unable to determine those coordinates, it would fallback to just loading the map with some default values.
You’ll notice that in my error method, I’m calling gMap.init() with no arguments, which I thought should mean that the variables lat and lon should be set to 57.700992 and 11.893836 respectively. Instead, I’m getting Uncaught TypeError: Cannot read property 'coords' of undefined. Where am I going wrong?
Also, in theApp.init() I’m calling the map if navigator.geolocation exists. Does that mean browsers that don’t support HTML5 geolocation will not even try loading the map?
var gMap = {
init: function (position) {
var lat = position.coords.latitude || 57.700992,
lon = position.coords.longitude || 11.893836,
geocoder = new google.maps.Geocoder(),
mapOptions = {
zoom: 12,
center: new google.maps.LatLng(lat, lon)
},
map = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);
},
error: function () {
console.log('failed to retrieve geoposition');
gMap.init();
}
}
var theApp = {
init: function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(gMap.init, gMap.error, {timeout:10000});
}
}
}
The
||you have there should work, unlessposition.coordsorpositionis undefined. In that case, JavaScript will throw a error because you’re trying to access a property on a undefined object.You will have to manually check if the objects exist:
If
positionis undefined, theifwill abort, without trying to check forposition.coords.(The
&&doesn’t evaluate the right parameter, if the left one is false)And yes, if
navigator.geolocationis undefined, the map will not be loaded:This ^ will not be executed, so
gMap.initwill not be executed.