over query limit also with setTimeout - google-maps

I'm trying to use google maps geocoder and getting over query limit.
this is my code
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 12,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
for (var i = 1; i < 20; i++) {
var address = document.getElementById('address' + " " + i).value;
setTimeout(geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
}));
}
}
google.maps.event.addDomListener(window, 'load', initialize, codeAddress.bind);

You didn't specify the delay(2nd argument of setTimeout)
You must set it to an incrementing value to avoid the error, e.g. i*150 , then the calls will be after 150ms,300ms,450ms and so on
function codeAddress() {
for (var i = 1; i < 20; i++) {
var address = document.getElementById('address' + " " + i).value;
setTimeout(geocoder.geocode({ 'address': address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' +
status);
}
}),
i*150//<-delay for the timeout in ms
);
}
}

Related

Find the business name associated with a street address with the Google Maps API?

Using the Google Maps Platform (Web JavaScript API), how do I find the business name associated with a street address?
I would expect PlacesService.textSearch() or PlacesService.findPlaceFromQuery() to return both "street_address" and "establishment" types when querying by an address associated with a business/establishment. However, when I search by street address, I only receive "street_address" results.
For example, when searching "400 West Anderson Ln, Austin, Texas", I want to know that "Austin Parke Apartments" are at this address. How can I do that?
geocode the address
use the places library nearbySearch to find places near that address
pick the closest result
var address = "400 West Anderson Ln, Austin, Texas";
geocoder.geocode({
address: address
}, function(results, status) {
if (status === 'OK') {
map = new google.maps.Map(document.getElementById('map'), {
center: results[0].geometry.location,
zoom: 15
});
latLng = results[0].geometry.location;
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: marker.getPosition(),
rankBy: google.maps.places.RankBy.DISTANCE,
types: ["establishment"]
}, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var marker = createMarker(results[i], i);
if (i == 0)
google.maps.event.trigger(marker, 'click');
}
} else {
alert('nearbySearch was not successful for the following reason: ' + status);
}
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
})
proof of concept fiddle
code snippet:
var map;
var infowindow;
var latLng;
var address = "400 West Anderson Ln, Austin, Texas";
function initMap() {
infowindow = new google.maps.InfoWindow();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: address
}, function(results, status) {
if (status === 'OK') {
map = new google.maps.Map(document.getElementById('map'), {
center: results[0].geometry.location,
zoom: 15
});
latLng = results[0].geometry.location;
console.log(results[0].geometry.location.toUrlValue(6))
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: marker.getPosition(),
rankBy: google.maps.places.RankBy.DISTANCE,
types: ["establishment"]
}, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(results.length + " results returned");
for (var i = 0; i < results.length; i++) {
var marker = createMarker(results[i], i);
if (i == 0)
google.maps.event.trigger(marker, 'click');
else
marker.setMap(null);
}
} else {
alert('nearbySearch was not successful for the following reason: ' + status);
}
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
})
}
function createMarker(place, index) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name + "<br>" + address + "<br>" + index);
infowindow.open(map, this);
});
return marker;
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry&callback=initMap" async defer></script>

Google API to map nearby properties in Salesforce

I asked this question originally in the Salesforce StackExchange, but was redirected here, since it's more of a Google API question than a Salesforce question.
Right now I have the following code, which creates a marker at the location of the property on a visualforce page that has an embedded Google Map. When the user clicks on the marker, an info window appears with information on the property.
<apex:page standardController="Property__c">
<head>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
</script>
<style>
#map {
font-family: Arial;
font-size: 12px;
line-height: normal !important;
height: 800px;
background: transparent;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</apex:page>
This is working just fine. But I am trying to modify it to also show properties nearby to this property. I have gotten as far as using an SOQL query to find these properties, pass their addresses into an array, geocode these addresses and set a marker at each geocoordinate. All of that works just swell.
Where I've been stuck, is in displaying the infowindow that appears when the user clicks one of these markers. Not only can I not create an infowindow for the NEW markers, but the infowindow for the OLD "main" marker is breaking as well. In fact, even if I comment the infowindow and listener events for the new markers, the original is still broken. These infowindows need to display different information than the infowindow for the "main" marker. Here is my modified code:
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var marker2;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
//several markers
//Get Geos
var geos = [];
var idy = 0; <
apex: repeat value = "{!getgeoList}"
var = "m" >
geos[idy++] = "{!m}"; <
/apex:repeat>
for (var i = 0; i < geos.length; ++i) {
console.log('geo' + geos[i] + 'out of' + geos.length);
geocodeAddress(geos[i]);
}
function geocodeAddress(location) {
geocoder.geocode({
'address': location
}, function(results, status) {
// alert(status);
if (status == google.maps.GeocoderStatus.OK) {
// alert(results[0].geometry.location+location);
createMarker(results[0].geometry.location, location);
} else {
alert("some problem in geocode" + status);
}
});
}
function createMarker(latlng, html) {
marker2 = new google.maps.Marker({
position: latlng,
map: map
});
addIinfo(marker2, html);
}
function addInfo(marker2, html) {
var infowindow2 = new google.maps.InfoWindow({
content: html
});
marker2.addListener(marker2, 'click', function() {
infowindow2.open(marker2.get('map'), marker2);
});
}
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
I changed marker2.addListener to google.maps.event.addListener. This worked, except that my original marker was showing the same information as the marker2 markers. When I changed the marker2 icon to blue, I realized that this was because it was putting a marker2 marker over the original marker. So I changed i = 0 to i=1 in my for loop, and now my code works just great! :)
Here is my new code:
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var marker2;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
//several markers
//Get Geos
var geos = [];
var idy=0;
<apex:repeat value="{!getgeoList}" var="m">
geos[idy++]="{!m}";
</apex:repeat>
for (var i = 1; i < geos.length; ++i) {
console.log('geo' + geos[i] + 'out of' + geos.length);
geocodeAddress(geos[i]);
}
function geocodeAddress(location) {
geocoder.geocode({
'address': location
}, function(results, status) {
// alert(status);
if (status == google.maps.GeocoderStatus.OK) {
// alert(results[0].geometry.location+location);
createMarker(results[0].geometry.location, location);
} else {
alert("some problem in geocode" + status);
}
});
}
function createMarker(latlng, html) {
marker2 = new google.maps.Marker({
position: latlng,
map: map,
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
addInfo(marker2,html);
}
function addInfo(marker2,html) {
var infowindow2 = new google.maps.InfoWindow({
content: html });
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map, marker2);
});
}
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});

Google Maps Nearby Search (Show Selected nearby markers only with autocomplete )

I have this code, which works fine, but there is just one issue which I am getting:
When we search nearby places, it appends the new nearby search markers with the old markers, screenshots are attached in these links.
Here I have searched the nearby banks:
http://prntscr.com/aouxra
It has successfully shown, but now if I search another nearby place like hotel, it will append its markers with the banks markers which has been searched previously, like this:
http://prntscr.com/aouz23
I want to only show the markers of the autocompleted nearby search query only.
function getNearby(lat,lng,map){
var availableTags = [
"hotel",
"bank",
"atm",
"school",
];
$( "#nearby" ).autocomplete({
source: availableTags,
select: function (event, ui) {
var request = null;
request = {
location: {lat:lat, lng:lng},
radius: 5500,
types: [ui.item.value]
};
var service = null;
var infowindow = null;
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
//var markers = [];
var markers = [];
var bounds = map.getBounds()
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++)
{
createMarker(results[i]);
//alert(results)
}
}
}
function createMarker(place) {
//markers.push(place);
var marker = '';
var placeLoc = '';
placeLoc = place.geometry.location;
marker = new google.maps.Marker({
map: map,
position: placeLoc
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
alert(markers.length);
}
});
}
function getLocation() {
$("#myNearby").css('display', 'block');
$("#directions").css('display', 'none');
$("#map").css('display', 'none');
$("#panel").css('display', 'none');
$("#load").css('display', 'none');
$("#googleMap").css('display', 'block');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
setLocationValue(position.coords.latitude,position.coords.longitude);
//getCurrentLocationValue(position.coords.latitude,position.coords.longitude);
var mapProp = {
center:new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
zoom:10,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var myMarker = new google.maps.Marker({
position: {lat:position.coords.latitude, lng:position.coords.longitude},
animation:google.maps.Animation.BOUNCE
});
myMarker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content:"You are Located in Lat: "+position.coords.latitude+' Lng: '+position.coords.longitude
});
infowindow.open(map,myMarker);
getNearby(position.coords.latitude,position.coords.longitude,map);
<?php /*?>$("#myNearby a").click(function(){
//alert('Working');
var request = {
location: {lat:position.coords.latitude, lng:position.coords.longitude},
radius: 5500,
types: [$("#location").val()]
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
});<?php */?>
}
function setLocationValue(lat,lng){
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
//console.log(results);
$.each(arrAddress, function(i, address_component) {
if (address_component.types[0] == "locality") {
itemLocality = address_component.address_components[0].long_name;
//console.log("City: " + address_component.address_components[0].long_name + itemLocality);
$("#location").val(itemLocality);
}
});
}
else{
alert("No results found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
});
}
Remove the existing markers from the map before showing the new ones. Make the markers array global, then do this at the beginning of getNearby:
for (var i=0; i<markers.length; i++) {
markers[i].setMap(null);
}
markers = [];

Google Maps API - Geocode & Search Nearby

I'm trying to merge together a GOOGLE geocoder script and a 'search nearby' script. I cannot seem to merge it successfully. Help?
The geocoder script lies here:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
And the search nearby script lies here:
var map;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
So I'm posting on here because I have no idea how to merge them. I tried to merge the scripts together but I couldn't get it to work. Any ideas?
Thanks.
Could be something like this sketch below.
Not sexy, but works.
Don't forget to include the places libary.
JS
var geocoder;
var map;
var infowindow;
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
var request = {
location: pyrmont,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = '100 Murray St, Pyrmont NSW, Australia';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
http://jsfiddle.net/iambnz/c9ovns0o/
EDIT:
Or you can simply copy and paste this html file, this should work.
http://lab.sourcloud.com/stackoverflow/26071099/
EDIT 2:
First geocode the address and then show places nearby.
var geocoder;
var map;
var infowindow;
//var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
var nearbysearchloc = '';
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = '100 Murray St, Pyrmont NSW, Australia';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
ParseLocation(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
function ParseLocation(location) {
var lat = location.lat().toString().substr(0, 12);
var lng = location.lng().toString().substr(0, 12);
nearbysearchloc = new google.maps.LatLng(lat, lng);
ShowPlacesAroundMe(nearbysearchloc);
}
function ShowPlacesAroundMe(location){
var request = {
location: location,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
google.maps.event.addDomListener(window, 'load', initialize);
http://jsfiddle.net/iambnz/c0omhyep/

Google Maps API v3 multiple markers Infowindow

I've used the code below to display a map with multiple markers and infowindows. Now I have encountered the very common problem of the last infowindow showing up on all markers. I've tried all sorts of solutions including: http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/ and this one http://www.robertbolton.com/blog/google-maps-v3-multiple-markers-and-infowindows-in-a-loop but none of them fix the problem.
Here is my code:
var infowindow = null;
var geocoder;
var map;
$(document).ready(function() {
initialize();
});
function initialize() {
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
setMarkers(map, people);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
}
var people = [
{"userid":"47","lastname":"lastname1","firstname":"firstname1","address":"Paris, France","phone1":"00000000000","phone2":"","email":"me#me.com"},
{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"Versaille, France","phone1":"0","phone2":"0","email":"me#me.com"}
];
function setMarkers(map, people) {
for (var i = 0; i < people.length; i++) {
var p = people[i];
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
geocoding is an asynchronous request. So when you use geocoding inside the for-loop, the loop is already finished when you receive the results, i will always be 1 and point to the last item of people.
What you can do: split the marker-creation into 2 functions. 1 for the loop which calls the 2nd function that creates the markers:
remove the current function setMarkers and add the following 2 functions to your script:
function setMarkers(map,people) {
for (var i = 0; i < people.length; i++) {
setMarker(map, people[i])
}
}
function setMarker(map, people) {
var p=people;
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
The rest of your script may stay as it is.