google maps over query limit - google-maps

I know that similar questions have been posted but I have not found and answer in any of them as it relates to my particular issue.
I have a javascript that uses google maps to place customer zipcodes on a map. The problem I am have is similar to what others have already posted – I get a “over query limit” error.
I have tried different setups using setTimeOut to try to send google the data within the allowable time intervals but I can’t get it to work.
Here is my action:
function initialize()
{
var rowNum = 0 ;
var rowColor = "" ;
var latlng = new google.maps.LatLng(27.91425, -82.842617);
var myOptions =
{
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
geocoder = new google.maps.Geocoder();
data.forEach(function(mapData,idx)
{
window.setTimeout(function()
{
geocoder.geocode({ 'address': mapData.address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: mapData.title,
icon: getIcon(mapData.type)
});
var contentHtml = "<div style='width:250px;height:90px'><strong>"+mapData.title+"</strong><br />"+mapData.address+"</div>";
var infowindow = new google.maps.InfoWindow({
content: contentHtml
});
google.maps.event.addListener(marker, 'click', function()
{
infowindow.open(map,marker);
});
marker.locid = idx+1;
marker.infowindow = infowindow;
markers[markers.length] = marker;
if (idx%2 == 0)
{
rowColor = 'style="background-color:#00FFFF;"' ;
}
else
{
rowColor = 'style="background-color:#FFFFFF;"' ;
}
var sideHtml = '<div ' + rowColor + ' class="loc" data-locid="'+marker.locid+'"><b>'+mapData.title+'</b><br/>';
sideHtml += mapData.address + '</div>';
$("#locs").append(sideHtml);
//Are we all done? Not 100% sure of this
if(markers.length == data.length) doFilter();
}
else
{
// alert("Geocode was not successful for the following reason: " + status);
}
}, 3000);
});
});
When I run my page using this action, I get back 11 markers even though I have many more than that in my JSON string. The window.setTimeout has absolutely no effect – I’m obviously doing something wrong here.
I would appreciate any help on this matter.
Thanks,

I found the answer to my question. I found the following code on the Web and modified it to my needs.
With it, you can load many markers without getting Over Query Limit from Google.
I have tested it with over 100 markers and it works beautifully. The page does not freeze up at all.
I am certain some of you guys can do something much more elegant and efficient but this is a good starting point.
<script type="text/javascript">
//<![CDATA[
// display ani gif
loadingGMap() ;
// delay between geocode requests - at the time of writing, 100 miliseconds seems to work well
var delay = 100;
// ====== Create map objects ======
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(27.989551,-82.462235);
var mapOptions =
{
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geo = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
// ====== Geocoding ======
function getAddress(search, next)
{
geo.geocode({address:search}, function (results,status)
{
// If that was successful
if (status == google.maps.GeocoderStatus.OK)
{
// Lets assume that the first marker is the one we want
var p = results[0].geometry.location;
var lat = p.lat();
var lng = p.lng();
// Output the data
var msg = 'address="' + search + '" lat=' +lat+ ' lng=' +lng+ '(delay='+delay+'ms)<br>';
//document.getElementById("messages").innerHTML += msg;
// Create a marker
createMarker(search,lat,lng);
}
// ====== Decode the error status ======
else
{
// === if we were sending the requests to fast, try this one again and increase the delay
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
{
nextAddress--;
delay++;
}
else
{
var reason = "Code "+status;
var msg = 'address="' + search + '" error=' +reason+ '(delay='+delay+'ms)<br>';
// document.getElementById("messages").innerHTML += msg;
}
}
next();
}
);
}
// ======= Function to create a marker
function createMarker(add,lat,lng)
{
var contentString = add;
if (add=='EOF')
{
stopLoadingGMap() ;
}
var addArray = add.split(' ');
var zipcode = addArray.pop();
var zipcode = add.match(/\d{5}/)[0] ;
var image = 'icons/sm_02.png';
var marker = new MarkerWithLabel(
{
position: new google.maps.LatLng(lat,lng),
map: map,
icon: image,
labelContent: zipcode,
labelAnchor: new google.maps.Point(50, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75},
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function()
{
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
// ======= An array of locations that we want to Geocode ========
// use static or build dynamically
// use as many markers as you need – I’ve test with over 100
var addresses = var data = [
{‘StreetAddress1 City State Zipcode’},
{‘StreetAddress2 City State Zipcode’},
{‘StreetAddress3 City State Zipcode’},
{‘StreetAddress14 City State Zipcode’},
…
{‘EOF’},
];
// ======= Global variable to remind us what to do next
var nextAddress = 0;
// ======= Function to call the next Geocode operation when the reply comes back
function theNext()
{
if (nextAddress < addresses.length)
{
setTimeout('getAddress("'+addresses[nextAddress]+'",theNext)', delay);
nextAddress++;
}
else
{
// We're done. Show map bounds
map.fitBounds(bounds);
}
}
// ======= Call that function for the first time =======
theNext();
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
//]]>
</script>

Related

Center map on user's location (Google Maps API v3)

I've looked a lot of various other reports about this problem, but I can't find the solution to get the location of user.
Here is my code:
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true'>
</script>
<script>
// prepare variables
var main = document.getElementById('main');
// async XHR request
var xhReq = new XMLHttpRequest();
xhReq.open('GET','../data/data.json', true);
xhReq.onload = function (e) {
if ((xhReq.readyState === 4) && (xhReq.status === 200)) {
// prepare external data
var data = JSON.parse(xhReq.responseText);
// prepare map
var map;
// var bounds = new google.maps.LatLngBounds();
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(54.6867151,25.2803843)
};
map = new google.maps.Map(main,mapOptions);
// add all data to the map
for(i=0;i<data.length;i++){
// loc = new google.maps.LatLng(data[i].lat,data[i].lng);
// bounds.extend(loc);
window['marker'+i] = new google.maps.Marker({
position: new google.maps.LatLng(data[i].lat,data[i].lng),
map: map,
title: data[i].name,
articles: data[i].articles
}
);
// add onClick function
google.maps.event.addListener(window['marker'+i], 'click', function() {
// magic should be here
var data = this.articles;
var list = document.getElementById('list');
var main = document.getElementById('main');
list.innerHTML = '';
list.style="width:25%;";
for(i=0;i<data.length;i++){
list.innerHTML += '<a href="' + data[i].url + '" target="_blank"><div class="listImg" style="background-image:url(' + data[i].img + ');"><\/div><span class="topic">(' + data[i].topic + ')<\/span> <h1>' + data[i].name + ' <\/h1><span class="date">(' + data[i].date + ')<\/span><\/a>';
};
});
};
// recenter + rezoom
// map.fitBounds(bounds);
// map.panToBounds(bounds);
};
};
xhReq.send(null);
</script>
It sets the center of map to exact coordinates which are in code.
Thanks for your support.
English isn’t my first language, so please excuse any mistakes.
Getting the user location is a browser feature that most modern browsers support. However, you still need to test for the ability to get the location in your code.
if (navigator.geolocation) { // test for presence of location feature
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
console.log('user denied request for position');
});
} else {
console.log('no geolocation support');
}

google places API - restrict to return full addresses only

Does anyone know a way to restrict Google Places API to return full address results only - ie those with the first two lines of an address.
I would like to cut out towns, and cities as they are too broad.
I see that postcodeanywhere provide full addresses only, however they don't have a free tier.
Thanks.
You have select which parameters you want to return from AUTOCOMPLETE ie street_number and route in your instance.
The basic usage is located here Google Maps JavaScript API.
Keep the following in mind; your input fields must be named per the Autocomplete parameters to work out of the box such as street_number, route, postal_code and so on or the API will not write to those fields inside your form.
Example JS from the fiddle I've included:
var placeSearch;
var componentForm = {
street_number: 'long_name',
route: 'long_name'
};
var mapOptions = {
center: new google.maps.LatLng(41.877461, -87.638085),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
disableDefaultUI: true,
streetViewControl: false,
panControl: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */
(
document.getElementById('field_autocomplete'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(12); // Why 17? Because it looks good.
}
marker.setIcon( /** #type {google.maps.Icon} */ ({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(25, 34),
scaledSize: new google.maps.Size(50, 50)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '')].join(' ');
}
infowindow.setContent('<div id="infowindow"><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
fillInAddress();
});
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
autocomplete.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
});
}
}
var componentForm is where you will specify which Autocomplete components you want to retrieve from the API.

google api to search nearby address using their latitude,longitude from database

I need to retrieve a set of nearby addresses from google api using their latitude,longitude values.Latitude,longitude values are retrieved from a database.Is there a way to accomplish this?
Use Google Maps Javascript Api.
https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
And Read a developer guide https://developers.google.com/maps/documentation/javascript/tutorial
Here is how it can be done with a combination of jquery and the google api. the $.getJSON call is invoking a service that gets a list of lat/lng objects in a pretty standard name and address kind of format and pushes everything into a marker array.
In this example the user enters an address in the "useradd" control, which becomes one blue marker, and some nearby things in the database are displayed as red markers.
I have found the map to be very sensitive to styling changes, especially modifying it's height and width, I am sure there is some way to deal with that, just have not found it yet.
<script type="text/javascript">
var geocoder;
var map;
var markersArray = [];
//---------------------------------------------------------------------------------------------------------------
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(0, 0); //add some real starting coords
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
$('#loadMsg').hide().ajaxStart(function () { $(this).show(); }).ajaxStop(function () { $(this).hide(); });
}
//---------------------------------------------------------------------------------------------------------------
function getStringfromJSON(invalue) {
if (!invalue) { return ''; } else { return invalue; }
}
function codeAddress() {
var address = document.getElementById("useradd").value;
if (address.length == 0) return;
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
geocoder.geocode
(
{ 'address': address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var blueIcon = new google.maps.MarkerImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, icon: blueIcon, clickable: false });
marker.setTitle(address);
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var dist = document.getElementById("selMiles").value;
var pageurl = '../Search/GetNearbys?lat=' + lat + '&lng=' + lng + '&dist=' + dist;
$.getJSON(pageurl,
function (data) {
for (var x = 0; x < data.length; x++) {
var facid = data[x].ID;
var facname = getStringfromJSON(data[x].Name);
var streetaddress = getStringfromJSON(data[x].StreetAddress);
var address2 = getStringfromJSON(data[x].Address2);
var city = getStringfromJSON(data[x].City);
var state = getStringfromJSON(data[x].State);
var zip = getStringfromJSON(data[x].ZipCode);
var xlat = data[x].Latitude;
var xlng = data[x].Longitude;
var xlatlng = new google.maps.LatLng(xlat, xlng);
var xmarker = new google.maps.Marker({ map: map, position: xlatlng, facilityid: facid });
xmarker.setTitle(facname + ' ' + streetaddress + ' ' + address2 + ' ' + city + ',' + state + ' ' + zip);
markersArray.push(xmarker);
google.maps.event.addListener(xmarker, 'click',
function () {
window.open('../Profile?id=' + this.facilityid, '_blank');
});
}
},
function (succeess) { }
);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
markersArray.push(marker); //put it here so it gets reset after each search
}
);
}
</script>

Removing Google Map markers from Map was working, now its not

As i am working on object oriented javascript, i have created one map object and as i need to maintain the all previous routes and markers i am not creating new Map object. My code is as follows
function map() {
this.defaultMapOption = {
center : new google.maps.LatLng(0, 0),
zoom : 1,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
this.map = null;
this.marker = [];
this.directionsDisplay = null;
}
map.prototype.init = function() {
this.map = new google.maps.Map(document.getElementById("map"), this.defaultMapOption);
var map1 = this.map;
var marker1 = this.marker;
var count = 0;
google.maps.event.addListener(this.map, 'click', function(event) {
count++;
$(".tabNavigation li").find("a[href=markers]").trigger('click');
if ( marker1[count] ) {
marker1[count].setPosition(event.latLng);
}
else
{
marker1[count] = new google.maps.Marker({
position: event.latLng,
map: map1,
draggable : true
});
//by clicking double click on marker, marker must be removed.
google.maps.event.addListener(map.marker[count], "dblclick", function() {
console.log(map.marker);
map.marker[count].setMap(null);//this was working previously
map.marker[count].setVisible(false);//added this today
$("#markers ul li[rel='"+count+"']").remove();
});
google.maps.event.addListener(marker1[count], "dragend", function(innerEvent) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': innerEvent.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.addMarkerData(results, count);
}
else
{
alert("Geocoder failed due to: " + status);
}
});
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.addMarkerData(results, count);
}
else
{
alert("Geocoder failed due to: " + status);
}
});
}
});
}
Only above code works for only one marker. Means first time marker get removed on double click. After that it wont work.
Any ideas that why its stopped working!
Your count value is incrementing with new markers and in addListener(map.marker[count],...) , count will contain the latest value. So only that marker will be deleted.
So you should be decrementing the count value at the end in the addListener function.
You're adding marker[1] but then you try to remove marker[0]. Move your count++; from the beginning to the end of the function.

Geocoding using Google Maps API v3 - Linking the original request to the response

I have a list of schools that I want to plot on a Google Map. I'm using Google's Geocoding Service to lookup the lng/lat for a given postcode, upon successfully retrieving this information I want to drop a marker, together with adding the appropriate event listener that opens an infobox when a given marker is clicked.
When I make a request to the geocoder it's in the context of a school, when I receive a callback I lose this context. You'll see from code below that I've come up with a clunky solution to this, although it fails occasionally when the geocoder results truncate the postcode.
Should I be using something like jQuery's Deferred Object to solve this issue?
var geocoder;
var map;
var infowindow
var iterator = 0;
geosearch = new Array();
function drop() {
for (var i = 0; i < schools.length; i++) {
setTimeout(function() { // delay added to prevent being throttled
addMarker();
iterator++;
}, i * 1000);
}
}
function addMarker() {
address = schools[iterator].addresses[0].address.zip;
geosearch[address] = schools[iterator]; // this is how I'm keeping track of initial request
geocoder.geocode( { 'address': address }, function(results, status) {
var school = geosearch[results[0].address_components[0].short_name]; // loading the school associated with the initial request, which only works if the postcode completely matches up - clunky!
if (status == google.maps.GeocoderStatus.OK) {
// each school has tags, I want to set a marker if certain tags exist
if ($.inArray('D', school.tags) > 0) {
var image = 'map_markers/brown_MarkerD.png';
} else if ($.inArray('C', school.tags) > 0) {
var image = 'map_markers/red_MarkerC.png';
} else if ($.inArray('B', school.tags) > 0) {
var image = 'map_markers/yellow_MarkerB.png';
} else if ($.inArray('A', school.tags) > 0) {
var image = 'map_markers/green_MarkerA.png';
} else {
var image = 'map_markers/blue_MarkerZ.png';
}
// add the marker to the map, using result
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
draggable: false,
icon: image,
shadow: 'http://www.google.com/mapfiles/arrowshadow.png',
animation: google.maps.Animation.DROP
});
// adds listening on marker so that popup box appears when clicked
google.maps.event.addListener(marker, 'click', (function(marker, school) {
return function() {
infowindow.setContent(
''+school.name+''
+'<address>'
+school.addresses[0].address.street+'<br />'
+school.addresses[0].address.city+'<br />'
+school.addresses[0].address.state+'<br />'
+school.addresses[0].address.zip+'<br />'
+school.addresses[0].address.country+'<br />'
+'</address>');
infowindow.open(map, marker);
}
})(marker, school));
} else {
console.log("* NOT found: " + status);
}
});
}
function initialise() {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(54.82659788452641,-3.417279296874991);
var mapOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
drop(); // loops through schools to add marker
}
I would suggest geocoding the addresses offline and storing the coordinates in your database (or wherever you are storing the addresses). Then use the coordinates to display the markers.
I would also suggest reviewing this article on geocoding strategies from the documentation
To answer your question, I would suggest using javascript function closures to associate the address with the callback function.
The problem I was experiencing here was just a questions of scope, and in particular the way that I was referencing the school within the addMarker() function. Rather than referencing the school within the schools array using the global iterator variable, I instead pass in this school, this way the correct school is always referenced on the callback that is created within this scope.
var geocoder;
var map;
var infowindow
var iterator = 0;
function drop() {
for (var i = 0; i < schools.length; i++) {
setTimeout(function() {
addMarker(schools[iterator]); // pass in the school as an argument
iterator++;
$('#current_school').text(iterator); // taken this out of addMarker()
}, i * 1000);
}
}
function addMarker(school) {
geocoder.geocode( { 'address': school.addresses[0].address.zip }, function(results, status) {
... // the inners from here remain the same
});
}