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:
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>