-1

I have a script which I can't get working. I keep getting the error 'Geocoder failed' but I am not sure why. It is supposed to get the long/lat and then reverse geocode it to show the street address in an alert box. I have tried ensuring that the browser is letting it share the location. I have also tried accessing via HTTPS as I read that this was needed now but it still doesn't work. If anyone can help me to get this working I would be most grateful! Thanks in advance.

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Current Location Address</title>
    <style>
    </style>
</head>



<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    alert("Geocoder failed");
}

  function initialize() {
    geocoder = new google.maps.Geocoder();



  }

  function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
        if (results[1]) {
         //formatted address
         alert(results[0].formatted_address)
        //find country name
             for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0;b<results[0].address_components[i].types.length;b++) {

            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                    //this is the object you are looking for
                    city= results[0].address_components[i];
                    break;
                }
            }
        }
        //city data

        alert(city.short_name + " " + city.long_name)


        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script> 
</head> 
<body onload="initialize()"> <font face="verdana">
        <!DOCTYPE html> 
If available, your current address will have been displayed in a message window. Please press 'Back' when finished.


</body>
</html>
Martyn
  • 73
  • 1
  • 3
  • 14
  • Use the second parameter passed to your `errorFunction` to learn more about the error. Example: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition – Pekka Jan 06 '17 at 20:32
  • Hi Pekka - thanks for the reply but I am not sure how to implement this. – Martyn Jan 06 '17 at 20:44

1 Answers1

0

Your errorFunction is automatically passed an error parameter that you can take a look at:

function errorFunction(error){
    alert("Geocoder failed: "+error.message);
}

See the MDN docs for more background and examples.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • Thanks for this, I added it to my script but when I run it I just get `Geocoder failed: ` displaying in the alert box. It doesn't seem to show any details. – Martyn Jan 06 '17 at 20:50
  • Hmm, strange. Does anything change when you switch `error.message` with `error.code`? – Pekka Jan 06 '17 at 20:54
  • That did change it, yes. Now I get `Geocoder failed: 2` but I am not sure what the 2 refers to. – Martyn Jan 06 '17 at 21:03
  • @Martyn see here: https://developer.mozilla.org/en-US/docs/Web/API/PositionError not sure the explanation is very helpful, though. Are you on a device that knows its location in the first place? Have you tried on a mobile device? – Pekka Jan 06 '17 at 21:28
  • I have tried loading it on a mobile device (iOS) and it asks for permission to use the location then interestingly it displays no error but does not return the alert box with the address... I really appreciate your help by the way, thanks very much! @Pekka 웃 – Martyn Jan 06 '17 at 21:51
  • You're welcome. What I would do next is put an `alert()` right in the `successFunction` call to see whether you're receiving valid coordinates. If that's the case, the problem is now further down the line. I'd download an extension for my browser that allows me to fake a location so I can debug it on the big machine. A Google search for ` extension fake location` should turn up what you need – Pekka Jan 06 '17 at 22:06