Fetch ISO-3166-2 code from Google Maps API. Is it possible? - google-maps

I need to match locations recorded with their coordinates (latitude/longitude) to the visitor's selection from an interactive map using region codes (ISO-3166-2).
Anyone has a take on this please? Not too sure how to go about it and/or if it's possible.

This is code for fetching region codes(ISO-3166-2) using google maps.
Fiddle Link
Js
var geocoder;
var map;
var marker;
codeAddress = function () {
geocoder = new google.maps.Geocoder();
var address = document.getElementById('city_country').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 16,
streetViewControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
mapTypeIds:[google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.ROADMAP]
},
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
draggable: true,
title: 'My Title'
});
updateMarkerPosition(results[0].geometry.location);
geocodePosition(results[0].geometry.location);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
map.panTo(marker.getPosition());
});
google.maps.event.addListener(map, 'click', function(e) {
updateMarkerPosition(e.latLng);
geocodePosition(marker.getPosition());
marker.setPosition(e.latLng);
map.panTo(marker.getPosition());
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
//updateMarkerAddress(responses[0].formatted_address);
for (var i = 0; i < responses[0].address_components.length; i += 1) {
var addressObj = responses[0].address_components[i];
for (var j = 0; j < addressObj.types.length; j += 1) {
if (addressObj.types[j] === 'country') {
updateMarkerAddress(addressObj.short_name);
}
}
}
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
html
<body>
<div id="panel">
<input id="city_country" type="textbox" value="Dublin, Ireland">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="mapCanvas"></div>
<div id="infoPanel">
<b>Marker status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Current position:</b>
<div id="info"></div>
<b>Fetched ISO-3166-2 code from Google Maps API:</b>
<div id="address"></div>
</div>
</body>
Disclaimer code modified from Fiddle

Related

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 API - get water body name

How can i get Water body name from google map api?
For example, when i click on map i choose "What's here?" popup will appear with lake name and coordinates. I need that name.
Lake Michigan is in the Places API at those coordinates. The "name" is "Lake Michigan / Michigan City" however.
Using the Google Maps Javascript API v3 Places Library:
code snippet:
var map;
var infowindow;
var service;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(43.4501005, -87.2220187),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: map.getCenter(),
radius: 500
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log("OK:" + results.length)
for (var i = 0; i < results.length; i++) {
console.log(results[i]);
var marker = createMarker(results[i]);
if (i == 0) google.maps.event.trigger(marker, 'click');
}
}
}
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 + "<br>place_id:" + place.place_id);
infowindow.open(map, this);
service.getDetails({
placeId: place.place_id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + '</div>');
infowindow.open(map, this);
});
google.maps.event.trigger(marker, 'click');
}
});
});
return marker;
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas"></div>

Google Maps 2 InfoWindows Auto-Opening infoWindow, 1 infoWindow after click

I have an auto-opening infoWindow.
I wish only two were opened automatically, while one did not. The effect Just like in the pictures.
My Code:
<script>
function initialize() {
var openedInfoWindow = [];
var locations = [
['Oddział', 52.846190, 17.723237, 3],
['Oddział', 52.812224, 17.201023, 2],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1]
];
var cityCircle;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3]),
map: map,
content: locations[i][0]
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i, infowindow) {
return function () {
if(openedInfoWindow[i] != null){
openedInfoWindow[i].close();
openedInfoWindow[i] = null;
}else{
infowindow.setContent(this.content);
infowindow.open(map, this);
openedInfoWindow[i] = infowindow;
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow[i] = null;
});
}
}
})(marker, i, infowindow));
google.maps.event.trigger(marker, 'click');
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(9);
google.maps.event.removeListener(listener);
});
}
function loadScript() {
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyADTnbl7e9y2o13cXkUFO8RZpXFJI-yzp4&' + 'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>`
Picture 1 = so now
Picture 2 = so it has to be
I would suggest you generalize it, add a member to your array to determine whether to open the marker or not.
var locations = [
// IW content, lat, lng, nowrap, open IW
['Oddział', 52.846190, 17.723237, 3, true],
['Oddział', 52.812224, 17.201023, 2, true],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1, false]
];
Then do this to open the infowindow:
if (locations[i][4]) {
google.maps.event.trigger(marker, 'click');
}
proof of concept fiddle
code snippet:
function initialize() {
var openedInfoWindow = [];
var locations = [
['Oddział', 52.846190, 17.723237, 3, false],
['Oddział', 52.812224, 17.201023, 2, true],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1, true]
];
var cityCircle;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3]),
map: map,
content: locations[i][0]
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i, infowindow) {
return function() {
if (openedInfoWindow[i] != null) {
openedInfoWindow[i].close();
openedInfoWindow[i] = null;
} else {
infowindow.setContent(this.content);
infowindow.open(map, this);
openedInfoWindow[i] = infowindow;
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow[i] = null;
});
}
}
})(marker, i, infowindow));
if (locations[i][4]) {
google.maps.event.trigger(marker, 'click');
}
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
map.setZoom(9);
google.maps.event.removeListener(listener);
});
}
function loadScript() {
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?' + 'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

How to drag marker and click to set at the same time in Google Maps API v3?

I'm new in Google Maps API v3, I'm trying to add click event listener to re-set the marker, but I want have the posibility to drag the marker too.
Actually I only can drag the marker, this is my code:
var lat = null;
var lng = null;
var map = null;
var geocoder = null;
var marker = null;
jQuery(document).ready(function(){
lat = jQuery('#lat').val();
lng = jQuery('#long').val();
jQuery('#pasar').click(function(){
codeAddress();
return false;
});
initialize();
});
function initialize() {
geocoder = new google.maps.Geocoder();
if(lat !='' && lng != '')
{
var latLng = new google.maps.LatLng(lat,lng);
}
else
{
var latLng = new google.maps.LatLng(11.027113, -63.862023);
}
var myOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: latLng,
draggable: true
});
updatePosition(latLng);
}
function codeAddress() {
var address = document.getElementById("direccion").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
updatePosition(results[0].geometry.location);
google.maps.event.addListener(marker, 'dragend', function(){
updatePosition(marker.getPosition());
});
} else {
alert("No podemos encontrar la direccion, error: " + status);
}
});
}
function updatePosition(latLng)
{
jQuery('#lat').val(latLng.lat());
jQuery('#long').val(latLng.lng());
}
I tried to add the following code:
myListener = google.maps.event.addListener(map, 'click', function(event) {
if(marker){marker.setMap(null)}
placeMarker(event.latLng);
google.maps.event.removeListener(myListener);
});
But it does not work.
I want to place the marker with both options, dragging and click. How I can achieve that in my code?
Thanks!
There is no placeMarker function in your code, and not sure why you only want the marker placed on the first click on the map (you are removing the listener after that). This is what I think you want:
var lat = null;
var lng = null;
var map = null;
var geocoder = null;
var marker = null;
var myListener = null;
jQuery(document).ready(function() {
lat = jQuery('#lat').val();
lng = jQuery('#long').val();
jQuery('#pasar').click(function() {
codeAddress();
return false;
});
initialize();
});
function initialize() {
geocoder = new google.maps.Geocoder();
if (lat != '' && lng != '') {
var latLng = new google.maps.LatLng(lat, lng);
} else {
var latLng = new google.maps.LatLng(11.027113, -63.862023);
}
var myOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: latLng,
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function() {
updatePosition(marker.getPosition());
});
updatePosition(latLng);
google.maps.event.addListener(map, 'click', function(event) {
if (marker) {
marker.setPosition(event.latLng)
} else {
marker = new google.maps.Marker({
map: map,
position: event.latLng,
draggable: true
});
}
updatePosition(event.latLng);
});
}
function codeAddress() {
var address = document.getElementById("direccion").value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
updatePosition(results[0].geometry.location);
google.maps.event.addListener(marker, 'dragend', function() {
updatePosition(marker.getPosition());
});
} else {
alert("No podemos encontrar la direccion, error: " + status);
}
});
}
function updatePosition(latLng) {
jQuery('#lat').val(latLng.lat());
jQuery('#long').val(latLng.lng());
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="lat" value="42" />
<input id="long" value="-85" />
<input id="pasar" type="button" value="geocode" />
<input id="direccion" value="New York, NY" />
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>

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.