0
votes

I am trying to use Google geocoding API. However I am getting following error even after mentioning API key This service requires an API key. For more information on authentication and Google Maps JavaScript API

Following is my HTML entry with API key:

<script src="//maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyAa7LqHyZpHtQBGR6415pYu1FnwWQBPcnY" type="text/javascript"></script>

and this is the angularjs code where I am getting REQEST_DENIED

    function geocode(dataset){
var coords = [];
var address = dataset.address;
var geocoder = new google.maps.Geocoder();
var defer = $q.defer();
geocoder.geocode({'address': address}, function( results, status ) {
        if (status === google.maps.GeocoderStatus.OK) {
            coords[0] = results[0].geometry.location.lat();
            coords[1] = results[0].geometry.location.lng();
            dataset["coordinates"]=results[0].geometry.location;
            defer.resolve(dataset);
        }
        else {
            coords = 'Could not retrieve coordinates for: ' + address;
            defer.reject();
        }
    });
return defer.promise;
}

Is there something I am missing? Thank you.

1
Just to mention Geocoding API is already enabled ;)Amit Pamecha
<script src="maps.google.com/maps/api/…> would this help ?Fadi Abo Msalam
I guess you forgot to specify which service you're going to use "key=...&libraries=places".DNM
have look into this accepted answer stackoverflow.com/questions/38028630/…user7760518
@FadiAboMsalam I added this <script async defer src="maps.google.com/maps/api/…> But this starts giving Google Maps API error: MissingKeyMapErrorAmit Pamecha

1 Answers

0
votes

So as per the comments above, when I checked network layer after executing fiddle from @FadiAboMsalam I could see the API key being sent into the request URL which was missing in my request. Am not sure why geocoder.geocode(....) is not sending api ley in my request. I changes this code to send $http request and it is giving proper repsonse. Here is the updated code:

  function geocode(dataset){
    var coords = [];
    var address = dataset.address;
    var geocoder = new google.maps.Geocoder();
    var defer = $q.defer();


 $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + 
            address + '&key=xxxxxxxx')
    .then(function(results){
     if (results.status === 200) {
        var data = results.data.results;
            dataset["coordinates"]=data[0].geometry.location;
            defer.resolve(dataset);
         }
         else {
             coords = 'Could not retrieve coordinates for: ' + address;
             defer.reject();
         }
     },
     function error(_error){
        defer.reject();
     });

    return defer.promise;
}

Thanks @PaulThomasGC and @FadiAboMsalam for useful inputs and others for investing your precious time.

Cheers!