Geolocation Uncaught TypeError: Cannot read property 'coords' of undefined
Solution 1
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.
Solution 2
The error is probably here
<body id="map" onload="initialize()">
You're calling the initialize function with no parameters. Therefore the 'position' parameter is undefined
function initialize(position) {
var lat = position.coords.latitude;
Its as if you called
var lat = undefined.coords.latitude
Related videos on Youtube
Comments
-
robabby over 1 year
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