Search code examples
google-mapsgoogle-cloud-platformgoogle-maps-api-3google-geocoder

Google Map key with Website application restriction


While applying application restrictions with 'Websites' option in Google cloud console for Map API key, it stopped working even in the allowed web url also.

Followed below steps:

  1. Enabled 2 API from API & Services (Maps JavaScript API, Geocoding API )
  2. Created API Key from Keys & Credentials
  3. Applied application restriction as we want to use this key from my hosted web page.

And We have below javascript snippet to call geocode api from client web app.

const latitude = 24.4564699;
const longitude = 54.4007989;

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var response = xhttp.responseText;
        try {
            const data = JSON.parse(response);
            if (data.status === "OK" && data.results && data.results.length > 0) {
                const formattedAddress = data.results[0].formatted_address;
                console.log("formattedAddress" + formattedAddress);
            } else {
                console.log("Location not found");
            }
        } catch (error) {
            console.log("Error parsing response");
            console.error(error);
        }
    }
};
let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=<MAP_API_KEY>`;
xhttp.open("GET", url, true);
xhttp.send();

But we are getting request_denied response.

{
   "error_message" : "API keys with referer restrictions cannot be used with this API.",
   "results" : [],
   "status" : "REQUEST_DENIED"
}

Solution

  • The web service which you are using can't use the key with referrer restrictions. Use the geocoder that is part of the JavaScript API v3 with the key with referrer restrictions.

    proof of concept fiddle (modified from example in docs)

    const latitude = 24.4564699;
    const longitude = 54.4007989;
    
    function initMap() {
      const map = new google.maps.Map(document.getElementById("map"), {
        center: {
          lat: latitude,
          lng: longitude
        },
        zoom: 8
      });
      const geocoder = new google.maps.Geocoder();
      const infowindow = new google.maps.InfoWindow();
      geocodeLatLng({
        lat: latitude,
        lng: longitude
      }, geocoder, map, infowindow);
    }
    
    function geocodeLatLng(latlng, geocoder, map, infowindow) {
      geocoder
        .geocode({
          location: latlng
        })
        .then((response) => {
          if (response.results[0]) {
            console.log(JSON.stringify(response.results[0]));
            if (response.results[0].viewport) {
              map.fitBounds(response.results[0].viewport)
              console.log("viewport")
            } //else if (response.results[0].)
            const marker = new google.maps.Marker({
              position: latlng,
              map: map,
            });
    
            infowindow.setContent(response.results[0].formatted_address + "<br>" + marker.getPosition().toUrlValue(6));
            infowindow.open(map, marker);
            setTimeout(500, function() {
              map.setCenter(latlng)
            })
          } else {
            window.alert("No results found");
          }
        })
        .catch((e) => window.alert("Geocoder failed due to: " + e));
    }
    
    window.initMap = initMap;
    #map {
      height: 100%;
    }
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <!doctype html>
    <html>
    
    <head>
      <title>Reverse Geocoding</title>
      <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    </head>
    
    <body>
      <div id="map"></div>
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly" defer></script>
    </body>
    
    </html>