I'm very new to javascript (read: today). I have the following to use HTML5 geocoding:
function geocode() {
var geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
var pos = geocodeWithHTML5();
alert('geocode - Lat: ' + pos.lat + ', Lng: ' + pos.lng);
}
}
function geocodeWithHTML5() {
navigator.geolocation.getCurrentPosition(function(position) {
var latlng = {
lat: parseFloat(position.coords.latitude),
lng: parseFloat(position.coords.longitude)
};
alert('navigator - Lat: ' + latlng.lat + ', Lng: ' + latlng.lng);
return latlng;
}, function() {
return false;
});
}
Alert navigator
works as expected.
Alert geocode
causes an error: Uncaught TypeError: Cannot read property 'lat' of undefined
.
I thought adding return
in front of navigator.geolocation.getCurrentPosition
might work, but it made no difference.
I'm sure I'm doing something obviously wrong here...
UPDATE: Changed to this, but now I get two alerts. The first has undefined
values, the second has the correct values:
function geocode() {
var geocoder = new google.maps.Geocoder();
// If browser supports HTML5 GeoLocation
if (navigator.geolocation) {
geocodeWithHTML5(function(pos){
alert('navigator - Lat: ' + pos.lat + ', Lng: ' + pos.lng);
});
} else {
// Alternative GeoLocation
}
}
function geocodeWithHTML5(fn) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: parseFloat(position.coords.latitude),
lng: parseFloat(position.coords.longitude)
};
fn(pos);
}, fn(false));
}