Search code examples
google-mapsgoogle-apps-scriptweb-applicationsgeolocation

How to get name of the location from Latitude and Longitude I am getting from google geocoder and display in web-app done using apps script


This is done for web app using apps script

I am able to read latitude and longitude using a geocoder from google. But when I try to get the location name from the JSON object, the web app can't display it. Then tried to display in an alert. And what? Yes, Alert can display the whole address. Then again tried to use the document.getElementById('id') to display same in webApp but can't display.

Here is my code for yetanotherDist.HTML GAS Project file.

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">

    <script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry" type="text/javascript"></script> 
    <script src="https://maps.googleapis.com/maps/api/js?key="APIKey"></script>
    <script src= "https://maps.googleapis.com/maps/api/js"></script>
    <script>
  window.onload = function() {
  var startPos;
  var geoOptions = {
    enableHighAccuracy: true
  }

    var geoSuccess = function(position) {
    startPos = position;
    document.getElementById('startLat').innerHTML = startPos.coords.latitude;
    document.getElementById('startLon').innerHTML = startPos.coords.longitude;
    var latlong = new google.maps.LatLng(currentLat, currentLong);

    fromLat =startPos.coords.latitude;
    fromLng = startPos.coords.longitude;
    toLat = 48.8567;
    toLng = 2.3508;
    distance = google.maps.geometry.spherical.computeDistanceBetween(
    new google.maps.LatLng(fromLat, fromLng), 
    new google.maps.LatLng(toLat, toLng));
    document.getElementById("Distance").innerHTML = distance;


    geocoder.geocode({'latLng':latlong}, function(results, status){
    if (status == google.maps.GeocoderStatus.OK)
    {
    if (results)
    {
    document.getElementById("Location").innerHTML = latlong;
    document.getElementById("Address").innerHTML = results[0].formatted_address;
    alert(results[0].formatted_address);
    }
    }
    else
    alert("Could not get the geolocation information");
    });

  };

    var geoError = function(error) {
    console.log('Error occurred. Error code: ' + error.code);
    // error.code can be:
    //   0: unknown error
    //   1: permission denied
    //   2: position unavailable (error response from location provider)
    //   3: timed out
  };
    navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
    
    </script>
  </head>
  <body>
<div id="startLat">startLat</div>
<div id="startLon">startLon</div>
<div id="Location">Location</div>
<div id="Address">Address</div>
<div id="Distance">Distance</div>
</body>
</html>

Here is the code.gs file

function doGet(e) {
  var htmlOutput =  HtmlService.createTemplateFromFile('yetanotherDist');

  return htmlOutput.evaluate();
}

Very interesting yet I am not able to understand why the location name can't be displayed in webapp. Or I might be missing something. Please help.


Solution

  • There are several errors in the code you posted which makes me wonder if that is the real code or just fantasy '-)

    https://maps.googleapis.com/maps/api/js?key="APIKey"
    

    There should not be that extra " before the key.

    You have not declared the GeoCoder reference yet you say that your code was able to find (&alert) the address - curious?!

    In the test I did I spoofed the location to Mt. Google by lat/lng using Dev Tools sensor and the geocoded result pinpoints Google HQ so I guess it works.

    <!DOCTYPE html>
    <html>
      <head>
            <style>
                div:before{content:attr(id)': ';color:red;}
                body{padding:5rem;font-family:courier}
            </style>
            <base target="_top">
    
            <script src="//maps.google.com/maps/api/js?libraries=geometry&key=APIKEY"></script>
            <script>
                window.onload = function() {
                    var startPos;
                    var geoOptions = {
                        enableHighAccuracy: true
                    };
    
    
                    let geocoder=new google.maps.Geocoder();
                    
                    
                    
                    var geoSuccess = function(position) {
                        startPos = position;
                        document.getElementById('startLat').innerHTML = startPos.coords.latitude;
                        document.getElementById('startLon').innerHTML = startPos.coords.longitude;
                        
                        var latlong = new google.maps.LatLng( startPos.coords.latitude, startPos.coords.longitude );
    
                        fromLat = startPos.coords.latitude;
                        fromLng = startPos.coords.longitude;
                        
                        toLat = 48.8567;
                        toLng = 2.3508;
                        
                        
                        distance = google.maps.geometry.spherical.computeDistanceBetween(
                            new google.maps.LatLng(fromLat, fromLng), 
                            new google.maps.LatLng(toLat, toLng)
                        );
                        document.getElementById("Distance").innerHTML = distance;
    
    
                        geocoder.geocode({'latLng':latlong}, function(results, status){
                            if (status == google.maps.GeocoderStatus.OK){
                                if (results){
                                    document.getElementById("Location").innerHTML = latlong;
                                    document.getElementById("Address").innerHTML = results[0].formatted_address;
                                }
                            } else {
                                alert("Could not get the geolocation information");
                            }
                        });
                    };
    
                    var geoError = function(error) {
                        console.log('Error occurred. Error code: ' + error.code);
                    };
                    
                    
                    navigator.geolocation.getCurrentPosition( geoSuccess, geoError, geoOptions );
                }
    
            </script>
        </head>
        <body>
            <div id="startLat">startLat</div>
            <div id="startLon">startLon</div>
            <div id="Location">Location</div>
            <div id="Address">Address</div>
            <div id="Distance">Distance</div>
        </body>
    </html>
    

    example output from faked location