Dak Dak - 1 month ago 8
Javascript Question

Javascript: Uncaught TypeError: Cannot read property 'lat' of undefined(…)

I am integrating Google Maps and the user places a pin on their location. I then use a dragend event to get the lat and lng. I have the following code, but I keep getting the following error:

Uncaught TypeError: Cannot read property 'lat' of undefined(…)


What is the issue?

<script type="text/javascript"
src="http://maps.google.com/maps/api/js?key=API_KEY">
</script>
<script type="text/javascript">
function initialize() {
var map;

var latlng = new google.maps.LatLng(-17.86389, 31.02972);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);

// Creating a marker and positioning it on the map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-17.86389, 31.02972),
map: map,
draggable:true,
title:"Drag pin to your exact store location."
});


google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("latbox").value = event.LatLng.lat();
document.getElementById("lngbox").value = event.LatLng.lng();

});

}

</script>
<div id="map_canvas" style="width:100%; height:100%"></div>
<input size="20" type="text" id="latbox" name="lat" >
<input size="20" type="text" id="lngbox" name="lng" >


I also have:

<body onload="initialize()">


Surely this should work?

Answer

JavaScript is case sensitive so you need to treat it that way.
Try

document.getElementById("latbox").value = event.latLng.lat();
document.getElementById("lngbox").value = event.latLng.lng();

(notice the lowercase l in latLng)