-1

The problem here is that Google returns "Over Query Limit" every time I run it. And I also seem to be unable to retrieve any destination suggestions from google whenever I use the search bar. and the latter issue seems to be connected to the former one. This Code used to get the user's current location, allow the user to insert their destination, plot a route between the source and destination and then pins the directions retrieved from Google's "Direction" API. Note that this project used to work just fine and then at one point it stopped working and we started receiving the error "Over Query Limit"

I've tried implementing the changes suggested in the following links to no avail:

  1. I've tried this

Code Below:

       <script>
            var latlng;
             var address;
            var places; 
            var dest;
            var L;
          function initMap() {
            var markerArray = [];
            // Instantiate a directions service.
            var directionsService = new google.maps.DirectionsService;
              //geocoder
            var geocoder = new google.maps.Geocoder();
            // Create a map and center it on Manhattan.
            var map = new google.maps.Map(document.getElementById('map'), {
              zoom: 20,
              center: {lat: 40.771, lng: -73.974}
            });
              //Current location
               infoWindow = new google.maps.InfoWindow;

              if (navigator.geolocation) {
              navigator.geolocation.getCurrentPosition(function(position) {
                 /* pos = {
                  lat: position.coords.latitude,
                  lng: position.coords.longitude
                }; */
                latlng = {lat: parseFloat(position.coords.latitude), lng: parseFloat(position.coords.longitude)};
        // This is making the Geocode request
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status !== google.maps.GeocoderStatus.OK) {
                alert(status);
            }
            // This is checking to see if the Geoeode Status is OK before proceeding
            if (status == google.maps.GeocoderStatus.OK) {
                address = (results[1].formatted_address);
            }
        });
                  var marker = new google.maps.Marker({
                    position: latlng,
                    map: map
                  });
                infoWindow.setPosition(latlng);
                infoWindow.setContent('current Location');
                infoWindow.open(map,marker);
                map.setCenter(latlng);
              }, function() {
                handleLocationError(true, infoWindow, map.getCenter());
              });
            } else {
              // Browser doesn't support Geolocation
              handleLocationError(false, infoWindow, map.getCenter());
            }
              //searchbar
               var input = document.getElementById('search');
            var searchBox = new google.maps.places.SearchBox(input);
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

            // Bias the SearchBox results towards current map's viewport.
            map.addListener('bounds_changed', function() {
              searchBox.setBounds(map.getBounds());
            });
      var markers = [];
             searchBox.addListener('places_changed', function() {
              places = searchBox.getPlaces();
              if (places.length == 0) {
                return;
              }
              // For each place, get the icon, name and location.
              var bounds = new google.maps.LatLngBounds();
              places.forEach(function(place) {
                if (!place.geometry) {
                  console.log("Returned place contains no geometry");
                  return;
                }
                var icon = {
                  url: place.icon,
                  size: new google.maps.Size(71, 71),
                  origin: new google.maps.Point(0, 0),
                  anchor: new google.maps.Point(17, 34),
                  scaledSize: new google.maps.Size(25, 25)
                };
                // Create a marker for each place.
                markers.push(new google.maps.Marker({
                  map: map,
                  icon: icon,
                  title: place.name,
                  position: place.geometry.location
                }));
                   dest = (places[0].formatted_address);
                if (place.geometry.viewport) {
                  // Only geocodes have viewport.
                  bounds.union(place.geometry.viewport);
                } else {
                  bounds.extend(place.geometry.location);
                }
              });
              map.fitBounds(bounds);
            });
            // Create a renderer for directions and bind it to the map.
            var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
            // Instantiate an info window to hold step text.
            var stepDisplay = new google.maps.InfoWindow;

            // Display the route between the initial start and end selections.
            calculateAndDisplayRoute(
                directionsDisplay, directionsService, markerArray, stepDisplay, map);
            // Listen to change events from the start and end lists.
            var onChangeHandler = function() {
              calculateAndDisplayRoute(
                  directionsDisplay, directionsService, markerArray, stepDisplay, map);
            };

            document.getElementById('search').addEventListener('change', onChangeHandler);
          }

          function calculateAndDisplayRoute(directionsDisplay, directionsService,
              markerArray, stepDisplay, map) {
            // First, remove any existing markers from the map.
            for (var i = 0; i < markerArray.length; i++) {
              markerArray[i].setMap(null);
            }
            // Retrieve the start and end locations and create a DirectionsRequest using
            // Driving directions.
            directionsService.route({
              origin: address,
              destination: document.getElementById('search').value,
              travelMode: 'DRIVING',
              provideRouteAlternatives: true
            }, function(response, status) {
              // Route the directions and pass the response to a function to create
              // markers for each step.
              if (status === 'OK') {
                  var routesSteps = [];
                var routes = response.routes;
                var colors = ['red','blue','purple'];
    console.log(response.routes);
                for (var i = 0; i < routes.length; i++) {
                            // Display the routes summary
                document.getElementById('warnings-panel').innerHTML += 'Route ' + i + ': via ' + routes[i].summary + '<br />';
                    new google.maps.DirectionsRenderer({
                        map: map,
                        directions: response,
                        routeIndex: i,
                        polylineOptions: {
                            strokeColor: colors[i],
                            strokeWeight: 4,
                            strokeOpacity: .2
                        }
                         });
                }
                showSteps(response, markerArray, stepDisplay, map);
              } else {
                window.alert('Directions request failed due to ' + status);
              }
            });
          }
          function showSteps(directionResult, markerArray, stepDisplay, map) {
              var x = directionResult.routes.length;
              var arr = [];
               console.log("Length",directionResult.routes.length);
               for (var i = 0; i <= x-1; i++) {
                   //console.log( directionResult.routes[i].legs[0].steps.length);
                   arr[i] = directionResult.routes[i].legs[0].steps.length;
                   console.log( directionResult.routes[i].legs[0]);  
               }
              console.log("array",arr);
              //console.log("Min", Math.min.apply(null, arr));
              console.log("Min", arr.indexOf(Math.min.apply(null, arr)));
              L = arr.indexOf(Math.min.apply(null, arr));

               //var myRoute = directionResult.routes[x-1].legs[0];
               var myRoute = directionResult.routes[L].legs[0];
            for (var i = 0; i < myRoute.steps.length; i++) {
              var marker = markerArray[i] = markerArray[i] || new google.maps.Marker;
              marker.setMap(map);
              marker.setPosition(myRoute.steps[i].start_location);
              attachInstructionText(
                  stepDisplay, marker, myRoute.steps[i].instructions, map);
            }  
          }
          function attachInstructionText(stepDisplay, marker, text, map) {
            google.maps.event.addListener(marker, 'click', function() {
              stepDisplay.setContent(text);
              stepDisplay.open(map, marker);
            });
          }
        </script>
Zyzzx
  • 45
  • 1
  • 11
  • How are you loading the API? Are you including a key? Does your key's billing account have a credit card associated with it? – geocodezip Apr 09 '19 at 19:58
  • @geocodezip yes we are using a key but no I do not have a credit card associated with it. – Zyzzx Apr 09 '19 at 20:01
  • That (not having a credit card associated with the key's billing account) would explain the over query limit issues. – geocodezip Apr 09 '19 at 21:28
  • @geocodezip i would agree except that, as i mentioned in the question, it did work before and i didnt have any credit card listed then. – Zyzzx Apr 09 '19 at 22:03
  • 1
    I suspect the policy changed recently (or maybe you ran through your "free" quota). – geocodezip Apr 09 '19 at 22:43

1 Answers1

0

It is possible that you have ran out of credits.

I suggest filing a support case via https://console.cloud.google.com/google/maps-apis/support. As it may involve you sharing Personal Identifiable Information about your project and billing account.strong text

Waren
  • 335
  • 2
  • 9
  • I have double checked the code several times and came to the conclusion that I came nowhere near running out of credit or depleting my free quota. Moreover, I went online and used my API key and realized that I'm only using 19 requests every time I run the code which, again, is nowhere near the free quota which is 2500 requests a day. – Zyzzx Apr 11 '19 at 23:56
  • Its still better to file a support case to get to the bottom of it. since youre experiencing quota errors it is most likely related to some change in your billing account. – Waren Apr 12 '19 at 00:06
  • Just letting you know that there is no "free quota" in the new Google Maps Platform. The "free quota" you are referring is the old model "Google Maps API". Google Maps Platform follows this new pricing https://cloud.google.com/maps-platform/pricing/sheet/ – rafon Apr 17 '19 at 02:55