Quota for Google Places API Autocomplete - google-maps

I a using Google Places API Web Service, Google Maps Directions API for a project where I am using Google Place Autocomplete for my search query. As of I know, I am supposed to get 2500 requests per day. The project is in testing mode. I am sure I have not searched that limit, but still, I am getting a console error You have exceeded your daily request quota for this API.
I am unable to figure out. Can anyone please help me on this issue.
Thanks in advance.
I have added in footer
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places&callback=WeddinginitMap">
</script>
And my script is:
<script>
//Direction Grand Cruise
function initDirection() {
var $directionMap = $('[ data-directionMap ]');
$.each($directionMap, function( index, element){
var $dirEle = $(element);
var that = $(this);
var $id = $dirEle.get(0).id;
var $start = $dirEle.closest('.modal-content').find('.start-move').get(0).id;
var $end = $dirEle.closest('.modal-content').find('.end-move').get(0).id;
//console.log($end);
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map($('#'+$id)[0] , {
zoom: 18,
center: {lat: 22.560941, lng: 88.354062}
});
var input = $('#'+$start)[0];
var autocomplete = new google.maps.places.Autocomplete(input);
directionsDisplay.setMap(map);
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
$('#'+$start)[0].addEventListener('change', onChangeHandler);
$('#'+$end)[0].addEventListener('change', onChangeHandler);
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: $('#'+$start)[0].value,
destination: $('#'+$end)[0].value,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
});//end $.each
};// initDirection
</script>
<script>
function WeddinginitMap() {
var $locationSelector = $('.map-wrapper').find('.location-map[ data-map ]');
$.each( $locationSelector, function( index, element ){
var $ele = $(element);
var $this = $(this);
var $mapId = $ele.get(0).id;
var $lat = parseFloat( $('#'+$mapId).data('lat') );
var $long = parseFloat($('#'+$mapId).data('longi'));
var $zoom = parseFloat( $('#'+$mapId).data('zoom') );
console.log($mapId);
console.log($lat);
console.log($long);
console.log($zoom);
var uluru = {lat: $lat, lng: $long };
var $map = $('#'+$mapId)[0];
var map = new google.maps.Map($map, {
zoom: $zoom,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
icon:'assets/img/svg/vivada-ico.svg'
});
});//$.each
initDirection();
};
</script>
<script>
function initializeGoogletMapinsideModal(){
$('.map-modal ').on('shown.bs.modal', function (e) {
WeddinginitMap();
initDirection();
});
};
initializeGoogletMapinsideModal();
function redirectToDirectionModal(){
var $closeModal = $('.close-modal');
$.each( $closeModal, function(index, element ){
var $elem = $(element);
$elem.on('click', function(){
var $MainModal = $elem.closest('.map-modal');
var $targetDirectionModal = $elem.attr('data-target-modal');
$MainModal.modal('hide');
$($targetDirectionModal).modal('show');
$($targetDirectionModal).on('shown.bs.modal', function(e){
initDirection();
});
});//click
});//$.each
};
redirectToDirectionModal()
</script>

Places API has 1000 daily requests by default
https://developers.google.com/places/web-service/usage
You should be aware that each time when you are typing a new symbol in the autocomplete you are sending a new request. So it is quite easy to exceed 1000 quota using autocomplete element.
You can enable Billing in your project in order to get 150K daily requests for Places API free of charge.
Hope this helps!
Update
Please note that Google changes the behavior starting from June 11, 2018. They migrate to Google Maps Platform.
https://cloud.google.com/maps-platform/user-guide/product-changes/

From my observation, I did not see any usage from my dashboard
I played around the autocomplete list in the search box many times, but I still get no usage record. The quota counts only when one of the place options is selected. I searched through the document and API doc, there is no explanation on how exactly the autocomplete feature is counted. However, I do not agree that it counts as a new request every time user types in a single character. If it does, the quota (1000 per day) will be used up in few minutes and usage will reach the cap easily. Most apps cannot survive.
I would say the autocomplete is counted only when one of the items is picked.

Related

google maps api findplace request not working properly

I want to display on my webpage the location from a JSON that has displayed a pharmacy name. The point is that google maps API is a little bit over my power of knowledge. I did a find-place request into the google maps API, but the location that is displayed is the one from my current location.
Here is the part of the code that would interest you
<div id="map"></div>
<script src="./keys.js"></script>
<script>
let map;
document.addEventListener("DOMContentLoaded", () => {
let s = document.createElement("script");
document.head.appendChild(s);
s.addEventListener("load", () =>
{
console.log("script has loaded");
x = navigator.geolocation;
x.getCurrentPosition(success, failure)
function success(position){
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
var coords = new google.maps.LatLng(myLat,myLong);
map = new google.maps.Map(document.getElementById("map"), {
center: coords,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
map: map,
position: coords,
})
}
function failure(){}
});
s.src = `https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=<%= "#{#medicament['farmacies'].first['name']}"%>&inputtype=textquery&fields=formatted_address,name,rating,opening_hours,geometry&key=**************`;
});
</script>
</div>
where <%= "#{#medicament['farmacies'].first['name']}"%> represents the name of the pharmacy from the html erb file.
What I found strange is that if I inspect the page where the location is the s.src takes me to a JSON that has all the right address information for the pharmacy.
Here you can see an image with the response from the API:
What I want is to point to the address of that pharmacy on google map. Any tips&tricks are very welcome!
Use google.maps.places.PlacesService.findPlaceFromQueryinstead.
Also see this tutorial.
var service = new google.maps.places.PlacesService();
var request = {
query: 'Museum of Contemporary Art Australia',
fields: ['name', 'geometry'],
};
const {results} = service.findPlaceFromQuery(request);

Google maps API not loading all markers - except on multiple reloads

I'm using Google's maps API with the geocoder API. But when the map initially loads it's not showing all the larkers. However, if I refresh/reload the paid several times, eventually all the markers load. I am aware that the rate limit is 2500 per day or 50 per second. My list of locations is only about 80 so shouldn't affect the daily limit, but could it be exceeding the 'per second' limit?
When the map isn't showing all the markers I get "TypeError: undefined is not an object (evaluating 'data.results[0].geometry')" in the console. Then after a few refreshes and all the markers are loaded I no longer get that error.
Is it possible to echo out any rate limit alerts from google?
Here is my code:
<script type="text/javascript">
$(document).ready(function () {
var map;
var elevator;
var myOptions = {
zoom: 6,
center: new google.maps.LatLng(53.027410, -1.801189),
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = [<?php
foreach ($addresses as $loc) {
echo "'".$loc."', ";
}
?>];
var markers=[];
var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
for (var x = 0; x < addresses.length; x++) {
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false&components=country:gb', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
markers.push(marker);
markerCluster.addMarker(marker);
});
}
});
</script>

Dynamic Load of Heatmap Data based on Map Bounds, Performance Issue

I have implemented a simple page that uses a listener to determine when a google maps bounds have changed because of zoom or pan. I am dynamically loading json data for a weighted heatmap summarized by the area visible in the map. It is working all except for the fact that I am not properly clearing the previous data from the heatmap on each call to the listener. Performance begins to degrade after the 4th or 5th call to fetch new data. I tried setting heatmap to null. What else is needed to maintain performance?
var map, heatmap;
var heatMapData = [];
function initMap() {
var uluru = { lat: 32.673363, lng: -97.399290 };
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: uluru
});
google.maps.event.addListener(map, "bounds_changed", function () {
heatmap = null;
var bounds = map.getBounds();
//TODO: implement async request
var Httpreq = new XMLHttpRequest(); // a new request
var boxRequest = 'HeatMapData?lmin=' + bounds.f.f + '&lmax=' + bounds.f.b + '&lnmin=' + bounds.b.b + '&lnmax=' + bounds.b.f;
Httpreq.open("GET", boxRequest, false);
Httpreq.setRequestHeader("Content-type", "application/json")
var heatMapJSON = Httpreq.responseText;
heatMapData = [];
var parsedJSON = JSON.parse(heatMapJSON);
for (var i = 0; i < parsedJSON.length; i++) {
heatMapData.push({ location: new google.maps.LatLng(parsedJSON[i].Lat, parsedJSON[i].Lon), weight: parsedJSON[i].weight })
};
console.info('map points: ' + parsedJSON.length.toString());
heatmap = new google.maps.visualization.HeatmapLayer({
data: heatMapData,
map : map
});
});
if (heatmap != null) {
heatmap.setMap(null);
};

How to get the lat and lng of dragged waypoint

I am making this app where I let the user draw a waypoints route with google maps directions service and currently I am working on the edit route page - that is where the user can drag the waypoints of the route to reorder them. I am having trouble getting the lat and lng of the currently dragged waypoint.
How can I access the lat/lng of the dragged waypoint object on drag end?
This is my code:
<script type="text/javascript">
var rendererOptions = {
draggable: true
};
var phpway = <?php echo json_encode($phpway); ?>;
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
var waypts = [];
for(var i = 0; i < phpway.length; i+=2){
waypts.push(new google.maps.LatLng(Number(phpway[i]), Number(phpway[i+1])));
}
var start = waypts[0];
var end = waypts[waypts.length-1];
var mywaypts = [];
var pointsArray = [];
for (var i = 1; i < waypts.length-1; i++) {
mywaypts.push({
location:waypts[i],
stopover:true});
}
var australia = new google.maps.LatLng(-25.274398, 133.775136);
function initialize() {
var mapOptions = {
zoom: 7,
center: australia
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
//computeTotalDistance(directionsDisplay.getDirections());
calcRoute();
});
calcRoute();
}
function calcRoute() {
console.log(start);
var request = {
origin: start,
destination: end,
waypoints: mywaypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
In the 'directions_changed' event handler, process through the "new" directions returned from:
directionsDisplay.getDirections(). The start/end locations of each leg are the waypoints (note that the end of the first leg will be the same point as the start of the second).
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
document.getElementById('waypoints').innerHTML = "";
var response = directionsDisplay.getDirections();
var route = response.routes[0];
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
document.getElementById('waypoints').innerHTML += legs[i].start_location.toUrlValue(6) +":";
document.getElementById('waypoints').innerHTML += legs[i].end_location.toUrlValue(6)+"<br>";
}
});
fiddle
Inspect var dirs = directionsDisplay.getDirections();, maybe using console.log(dirs); to get a glance at the request format.
You will find the origin under dirs.request.origin, the destination under dirs.request.destination and the waypoints under dirs.request.waypoints.
To find the waypoint you have just ended dragging, keep the previous request (there should always be one, even before the first drag, since you first load the the route to be edited) and search for the differences in between this previous request and the current one via a simple iteration through the 'set of waypoints'. I suspect that there should be only one difference you find between the two (no matter if you introduce a new waypoint or you move an already existing one). That is your last dragged waypoint.

How to load markers from XML file with directions API in Google Maps

I'm trying to load markers from XML file on a map used for outputing directions. Basically, it's the combination of two demos found on Google's documentation pages.
Directions: https://google-developers.appspot.com/maps/documentation/javascript/examples/directions-panel
XML: http://gmaps-samples-v3.googlecode.com/svn/trunk/xmlparsing/downloadurl_info.html
I have first created the directions map and then tried to add XML file that contains markers.
I'm probably making a simple mistake, but since I'm not good with js and coding, can't find what. There are no errors displayed, only a blank page.
Here is my current code:
<script>
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
var control = document.getElementById('control');
control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP].push(control);
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("http://gmaps-samples-v3.googlecode.com/svn/trunk/xmlparsing/moredata.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(markers[i].getAttribute("name"), latlng);
}
});
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here is the (non-working) jsFiddle: http://jsfiddle.net/ajJ3u/
Problems from a quick review:
you are creating the map twice.
you don't have a createMarker function. If that call came from one of the examples, you missed bringing it to the new map.
downloadUrl is subject to a cross-domain security restriction. If your page is not running in the "http://gmaps-samples-v3.googlecode.com" domain, it won't work. You need to access xml from the same domain as the page is running in or use a proxy.
Example of directions from/to markers from xml (translated to v3 from Mike Williams' v2 tutorial