Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  42] [ 7]  / answers: 1 / hits: 17816  / 12 Years ago, thu, november 15, 2012, 12:00:00

I'm messing with the Google Maps API with Geolocation. Everything is working as expected, however I keep getting this error in my console:



Uncaught TypeError: Cannot read property 'coords' of undefined



Here is my Geo Check:



// Does this browser support geolocation?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize, locationError);
} else {
showError(Your browser does not support Geolocation!);
}


My Success Handler:



function initialize(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var acc = position.coords.accuracy;

// Debugging
console.log(position.coords);
console.log(Accuracy: +acc+nLatitude: +lat+nLongitude: +lon);

// Google Maps API
var myLatlng = new google.maps.LatLng(lat,lon);
var mapOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(map_canvas), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:Hello World!
});
}


I then initialize the map in my body tag <body id=map onload=initialize()>



The map renders fine, everything is working as expected. When I log position.coords to my console, I get a clean readout. Why do I keep receiving this error?



Google and SO searches rendered no results...



Cheers


More From » google-maps

 Answers
12

When document is loaded, the initialize method is called with no argument.
That's why you get the error.



Try this way instead:



function initCoords() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize, locationError);
} else {
showError(Your browser does not support Geolocation!);
}
}


and in your html code:



<body id=map onload=initCoords()>



Keep the initialize function as is.


[#81967] Wednesday, November 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janayr

Total Points: 80
Total Questions: 80
Total Answers: 114

Location: Venezuela
Member since Sat, Aug 22, 2020
4 Years ago
;