Here is the code:
<script type="text/javascript">
var offender_locations = [
["10010", "xxxxx", 3],
["10001", "xxxxx", 2],
["10002", "zzzzz", 1]
];
for (i = 0; i < offender_locations.length; i++) {
var address = offender_locations[i][0];
var icon_img = offender_locations[i][1];
}
</script>
This is the output:
1) 10010 - zzzzz
2) 10001 - zzzzz
3) 10002 - zzzzz
AS you can see var address outputs the correct value, but *var icon_img* does always repeat the same value.
I am a Javascript beginner and I have tried all ways I can think of but I still get the same results.
P.S. I have pasted the full script here :
<script type="text/javascript">
var offender_locations = [
["10010", "offender_icon.png", 3],
["10001", "offender_icon.png", 2],
["10002", "visitor_icon.png", 1]
];
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var latlng = new google.maps.LatLng(0, 0);
for (i = 0; i < offender_locations.length; i++) {
var infowindow = new google.maps.InfoWindow();
var geocoder_map = new google.maps.Geocoder();
var address = offender_locations[i][0];
var icon_img = offender_locations[i][1];
geocoder_map.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: map.getCenter(),
icon: icon_img
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(offender_locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
} else {
alert("The requested offender is not mappable !")
};
});
}
</script>
The markers in this script are all # the correct postal code, but they all show the same icon (visitor_icon.png) !
The problem is that you are creating a function in a loop. JavaScript has only function scope, not block scope. I.e. variables you create in a loop exist only once in the whole function, just the values changes per iteration.
At the time icon_img is evaluated (in the callback passed to geocode), the outer for loop already finished and icon_img has the value of the last iteration. It works for address because it is evaluated inside the loop, not later.
You have to 'capture' the current value of icon_img and you can do so by using an immediate function:
for (i = 0; i < offender_locations.length; i++) {
var infowindow = new google.maps.InfoWindow(),
geocoder_map = new google.maps.Geocoder(),
address = offender_locations[i][0],
icon_img = offender_locations[i][1];
(function(addr, img) { // <-- immediate function call
geocoder_map.geocode({'address': addr}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
icon: img
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(addr);
infowindow.open(map, marker);
});
} else {
alert("The requested offender is not mappable !");
}
});
}(address, icon_img)); // <-- immediate function call
}
Maybe you hav to do this for even more variables... not sure.
Related
Background to Question
I have an array which includes latitude and longitude values. I have the below code which places a marker for each iteration. I am using a Ruby gem Gon to pass values from the database to javascript. The below is working as expected:
function populateMap(map){
var index;
for (index = 0; index < gon.length; ++index) {
var latlng = new google.maps.LatLng(gon.murals[index].lat, gon.murals[index].long);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
}
}
However I want to have an info window for each marker with the address. This is done by reverse geo-coding. https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse.
The below code works for reverse geocoding 1 marker:
function getReverseGeocodingData(geocoder, map, infowindow) {
var latlng = new google.maps.LatLng(gon.murals[0].lat, gon.murals[0].long);
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[1]) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'mouseover', function () {
infowindow.open(map, marker);
document.getElementById("address").innerHTML = results[1].formatted_address ;
});
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
Actual Question
When I add the for loop to the reverse geo0code function it only places the marker of the last iteration.
function populateMapTest(map, geocoder, infowindow){
var index;
for (index = 0; index < gon.murals.length; ++index) {
var latlng = new google.maps.LatLng(gon.murals[index].lat, gon.murals[index].long);
alert("start of iteration: " + index);
geocoder.geocode({'location': latlng}, function(results, status){
alert("middle of iteration: " + index);
if (status === 'OK') {
if (results[1]) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'mouseover', function () {
infowindow.open(map, marker);
document.getElementById("address").innerHTML = results[1].formatted_address ;
});
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
alert("end of iteration: " + index);
}
}
For each iteration the alerts are in the following order: Start of iteration, end of iteration, middle of iteration. It seems to be skipping over the code contained in the geocoder brackets till all the iterations are done. I think?
Any help appreciated.
This sounds like a class closure problem, which relates to the scope of a variable that is declared in a high scope but used in functions that are in a lower scope and persist longer than the higher scope where the variable was actually declared.
Change:
var index;
for (index = 0; index < gon.murals.length; ++index) {
to:
for (let index = 0; index < gon.murals.length; ++index) {
This will give index block level scope and each iteration of the loop will have its own value for index. Instead of all iterations of the loop sharing the same index value, each will get its own.
It does seem like a closure issue. But I think it could be because of the variable latlng instead of the index, (or both).
var latlng = new google.maps.LatLng(gon.murals[index].lat, gon.murals[index].long);
The latlng above is updated throughout the loop but eventually the function uses only the last iteration's latlng. The variables inside the closure (the "middle" function) are referenced and will all be updated to the last value when the function actually executes. (I guess a different way of thinking about it, is that it really only looks at the value during execution instead of declaration)
var marker = new google.maps.Marker({
position: latlng,
map: map
});
And at the end, the marker would just be created at the same position, index times.
As an example, the code below will print ten 9s even if you expect it to print an increasing x
function foo() {
for (let index = 0; index < 10; ++index) {
var x = index;
setTimeout(function bar() {
console.log(x)
}, 10)
}
}
foo()
But this will print it correctly if it was immediately invoked (but of course, this isn't an option for your case)
function foo() {
for (let index = 0; index < 10; ++index) {
var x = index;
setTimeout(function bar() {
console.log(x)
}(), 10)
}
}
foo()
You could move the latlng declaration inside the middle function. (Do check the value of the index too though, because that suffers the same issue)
How about this :
geocoder.geocode({'location': latlng}, (function(indexCopy){
return function(results, status) {
alert("middle of iteration: " + indexCopy);
if (status === 'OK') {
if (results[1]) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'mouseover', function () {
infowindow.open(map, marker);
document.getElementById("address").innerHTML = results[1].formatted_address ;
});
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
};
})(index));
Just a thought...
I am using Google map api v3 to plot markers of location array. My script is
function OnSuccess(response) {
var markers = response.d.split('^^');
var latlng = new google.maps.LatLng(51.474634, -0.195791);
var mapOptions1 = {
zoom: 14,
center: latlng
}
var geocoder = new google.maps.Geocoder();
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions1);
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, 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,
title: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
(function (marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data);
infoWindow.open(map, marker);
});
})(marker, data);
}
where markers variable is bringing proper data, my test data is array of 5 elements
The Game Larder, 24 The Parade, Claygate, Surrey,KT10 0NU
24 The Parade, Claygate, Esher, Surrey KT10 0NU
Card Collection, 14 The Parade, Claygate, ESHER, KT10 0NU
16A The Parade, Claygate, ESHER, KT10 0NU
and same is coming into array markers however it is plotting only two markers. What could be wrong here
Solution
I was entering locations which are very close to each other e.g 1 and 2 point which gives same latlong hence mark as one place. I found latlong here. Thanks for answers btw :)
In page.aspx. insert tag <div id="map-canvas" ></div>
view source page.aspx and insert script into it>
var lis_marker = new Array();
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
lis_marker[i] = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
there are difference with your code:
1: var lis_marker = new Array();
2: lis_marker[i] = new google.maps.Marker({...});
In the example fiddle, how can I get the total number of markers displayed on the map? I'm pushing each of the markers into an array like this:
markers.push(marker)
And attempting to get the total number of markers like this:
$('.marker-count span').html(markers.length);
Unfortunately, "markers.length" is returning 0 when it should be returning at least 3.
I have example code here: http://jsfiddle.net/287C7/
How can I display the total number of markers? Is it not possible to add each marker to my array?
I need to know the amount of markers shown so that I can alert the user if there are none.
Thanks,
In case you don't want to view the code on jsfiddle.net, here it is:
var map, places, tmpLatLng, markers = [];
var pos = new google.maps.LatLng(51.5033630,-0.1276250);
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(51.5033630,-0.1276250)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// create the map and reference the div#map-canvas container
var markerBounds = new google.maps.LatLngBounds();
var service = new google.maps.places.PlacesService(map);
// fetch the existing places (ajax)
// and put them on the map
var request = {
location: pos,
radius: 48000, // Max radius
name: "mc donalds"
};
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
$('#map-canvas').attr("data-markers",results.length);
$('.marker-count span').html(markers.length);
} else {
console.log("Places request failed: "+status);
}
} // end callback
function createMarker(place) {
var prequest = {
reference: place.reference
};
var tmpLatLng = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
markers.push(marker);
markerBounds.extend( tmpLatLng );
} // end createMarker
service.nearbySearch(request, callback);
the placesSearch call is asynchronous, when you run your code:
$('.marker-count span').html(markers.length);
the result hasn't come back from the server yet. You need to do that in the call back after you update the markers array.
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
$('#map-canvas').attr("data-markers",results.length);
$('.marker-count span').html(markers.length);
} else {
console.log("Places request failed: "+status);
}
} // end callback
working fiddle
I have a problem because i want to use this Json Result that returns Json List but my problem is how should i call the json result that i will be using to geocode and add marker to my Google Maps ? I used getJson and its not functioning but i dont tried yet the .ajax function
Here is my sets of codes:
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
var minZoomLevel = 4;
var zooms = 7;
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Bounds for North America
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(15.70, -160.50),
new google.maps.LatLng(68.85, -55.90)
);
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function () {
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
}
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
function codeAddress() {
var infowindow = new google.maps.InfoWindow();
$.getJson("Dashboard/DashboardIndex",null , function(address) {
$.each(address, function () {
var currVal = $(this).val();
address.each(function () {
geocoder.geocode({ 'address': currVal }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
icon: iconBase + 'man.png',
position: results[0].geometry.location,
title: currVal
})
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(currVal);
infowindow.open(map, marker);
}
})(marker, currVal));
address.push(marker);
}
else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(codeAddress, 2000);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
});
});
return false;
}
window.onload = function () {
initialize();
codeAddress();
}
</script>
And my JsonResult at my Controller
public JsonResult LoadWorkerList()
{
var workerList = new List<Worker_Address>();
// check if search string has value
// retrieve list of workers filtered by search criteria
var list = (from a in db.Worker_Address
where a.LogicalDelete == false
select a).ToList();
List<WorkerAddressInfo> wlist = new List<WorkerAddressInfo>();
foreach (var row in list)
{
WorkerAddressInfo ci = new WorkerAddressInfo
{
ID = row.ID,
Worker_ID = row.WorkerID,
AddressLine1 = row.Address_Line1 + " " + row.Address_Line2+ " " +row.City + " "+ GetLookupDisplayValById(row.State_LookID),
LogicalDelete = row.LogicalDelete
};
wlist.Add(ci);
}
return Json(wlist.ToList().OrderBy(p => p.AddressLine1), JsonRequestBehavior.AllowGet);
}
Im thanking some who could help me in Advance :)
It's hard to guess where it goes wrong since you didn't post the JSON format and are getting errors (toLowerCase) of code you haven't posted. I think it's in the following area:
function codeAddress() {
var infowindow = new google.maps.InfoWindow();
$.getJson("Dashboard/DashboardIndex",null , function(address) {
console.log("full json object",address);//<--should show an array of objects
$.each(address, function () {
console.log(this);//<--here you can see what the JSON object is
var currVal = this["AddressLine1"];//<--guess from what your C# code looks like
//next each doesn't make much sense unless you have an array of arrays
// but the C# code makes json for a list (not a list of lists)
You can use IE for your console output but don't bother posting the output here because I can already tell you it's going to be [Object, object]. To get useful info you're going to have to use firefox with firebug or Chrome. To see the console you can press F12
The line:
setTimeout(codeAddress, 2000);
Could be optimized since now when you are making too many requests you'll fetch the entire address list again and start from the beginning instead of "waiting" for 2 seconds and continue where you were.
The following code:
map.setCenter(results[0].geometry.location);
Why set the center of the map within the loop? It'll just end up having the center of the last found address so you may as well do it outside the loop to set the center to last found address.
I'm sure this is really simple but I haven't had much luck figuring out what's wrong. I'm creating an empty array (locations), filling it with location objects in the getPartnerLocations function and then trying to plot the locations on the map with the drop function. The problem I'm having is that inside the drop function the locations array which has stuff in it is returning a length of zero so the loop in the isn't working. Any tips or ideas about what's going on here would be greatly appreciated.
var markers = [];
var locations = [];
var iterator = 0;
var map;
var geocoder;
var newYork = new google.maps.LatLng(40.7143528, -74.0059731);
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: newYork
};
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
}
function getPartnerLocations() {
geocoder = new google.maps.Geocoder();
$('.partner').each(function(index){
var street = $('.partner-streetaddress',this).text();
var city = $('.partner-city',this).text();
var state = $('.partner-state',this).text();
var country = $('.partner-country',this).text();
var address = street + ', ' + city + ', ' + state + ', ' + country;
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
locations.push( results[0].geometry.location );
console.log(locations[index]);
}
else
{
console.log('failed to geocode address: ' + address);
}
});
});
initialize();
drop();
}
function addMarker() {
console.log('add marker function');
markers.push(new google.maps.Marker({
position: locations[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP
}));
iterator++;
}
function drop()
{
console.log(locations.length);
for (var i = 0; i < locations.length; i++) {
setTimeout(function() {
addMarker();
}, i * 200);
}
}
getPartnerLocations();
geocode is an asynchronous function.
The callback doesn't execute until some time after you call drop.
Therefore, when you call drop, the array is still empty.
You need to call initialize and drop after the last AJAX call replies, in the geocode callback.