Location
property is represented as a google.maps.LatLng
object, which requires explicit conversion to display lat/lng values, for example:
var sval = results[0].geometry.location.toString();
You can also access the lat/lng values using specific functions:
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
To obtain a string representation of the Location
property, you could replace:
alert(JSON.stringify(results[0].geometry));
with:
alert(JSON.stringify(results[0].geometry, convertLatLngValue, 4));
where
function convertLatLngValue(key, value)
{
if (key == "lat" || key == "lng") {
return value();
}
else {
return value;
}
}
Live demonstration
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var json = JSON.stringify(results[0].geometry, convertLatLngValue, 4);
document.getElementById('output').innerHTML = json;
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocoding was not successful due to: ' + status);
}
});
}
function convertLatLngValue(key, value)
{
if (key === "lat" || key === "lng") {
return value();
}
else {
return value;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
height: 240px;
margin: 0px;
padding: 0px;
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="panel">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
<pre id="output"></pre>