Reverse Geocoding converting coordinates into address?

Ollie Jones picture Ollie Jones · May 12, 2012 · Viewed 7.9k times · Source

Am I missing something completely obvious here?

My intention is to convert the coordinates into an address and insert it into a div

http://jsfiddle.net/sHLG6/1/

Thank you

Answer

Pete picture Pete · May 13, 2012

I saw 3 things that popped out immediately with your fiddle.

  1. You never referenced the Google javascript libraries
  2. You never called initialize() and codeLatLng()
  3. You used the value property on the div element but what you really wanted was the getAttribute() method.

I changed your fiddle so it's working now

For the sake of completeness, the original code was as follows

<div id="latlng" value="54.9882,-1.5747"></div>
<div id="test"></div>
var geocoder; function initialize() {
geocoder = new google.maps.Geocoder(); } function codeLatLng() {

    var input = document.getElementById("latlng").value;
    var latlngStr = input.split(",", 2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({
        'latLng': latlng
    }, function(results, status) {

        document.getElementById("test").innerHTML = '' + (results[4].formatted_address); + ''
    }); }​

Working code:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="latlng" value="54.9882,-1.5747"></div>
<div id="test"></div>
var geocoder;
initialize();
codeLatLng();
function initialize() {

    geocoder = new google.maps.Geocoder();
}

function codeLatLng() {

    var input = document.getElementById("latlng").getAttribute('value');
console.log(input);
    var latlngStr = input.split(",", 2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({
        'latLng': latlng
    }, function(results, status) {

        document.getElementById("test").innerHTML = '' + (results[4].formatted_address); + ''
    });
}​