Google Maps v3 using markers that move about the map - javascript

http://rca2.com/mapping/thispageblinks.htm
http://rca2.com/mapping/doesnotremove.htm
The second example really doesn't do anything without continuously updated xml data.
I'm converting (finally!) my map applications from Google v2 to v3. In v2, the application read in xml data every 5 seconds, cleared markers, then new markers were created and placed on the map. The ability to clear the map overlay using map.clearOverlays() no longer exists in v3. The suggested solution is to keep track of the old markers, then remove them. Clearing the markers in a loop prior to creating new markers is easy to do, and works. Except for the fact that the markers blink when replaced more often than not. This is very distracting, and highly undesirable since this did not happen in v2.
I decided that I should compare the new marker data to the old marker data. If the location and icon color stayed the same, both old and new markers are basically ignored. For the sake of clarity, the icon color signifies a status of the vehicle represented by the icon. In this case the application is to track ambulance activity, so green would be available, blue would be en-route, etc.
The code handles the checking of the new and old markers fine, but for some reason, it will never remove the old marker when a marker (unit) moves. I saw suggestions about setMap() being asynchronous. I also saw suggestions about the arrays not being google.maps.Marker objects. I believe that my code handles each of these issues correctly, however the old markers are still never removed.
I've also made sure that my marker arrays are global variables. I am also using the variable side_bar_html to display information about which markers were supposed to be removed, and which markers were supposed to be added. The added markers are being added just fine. I just don't know where to turn next. Any help you could offer would be greatly appreciated.
function getMarkers() {
// create a new connection to get our xml data
var Connect = new XMLHttpRequest();
// send the get request
Connect.open("GET", xml_file, false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
// Place the response in an XML document.
var xmlDoc = Connect.responseXML;
// obtain the array of markers and loop through it
var marker_data = xmlDoc.documentElement.getElementsByTagName("marker");
// hide the info window, otherwise it still stays open where a potentially removed marker used to be
infowindow.close();
// reset the side_bar and clear the arrays
side_bar_html = "";
markerInfo = [];
newMarkers = [];
remMarkers = [];
addMarkers = [];
// obtain the attributes of each marker
for (var i = 0; i < marker_data.length; i++) {
var latData = marker_data[i].getAttribute("lat");
var lngData = marker_data[i].getAttribute("lng");
var minfo = marker_data[i].getAttribute("html");
var name = marker_data[i].getAttribute("label");
var icontype = marker_data[i].getAttribute("icontype");
var unitNum = marker_data[i].getAttribute("unitNum");
var llIcon = latData + lngData + icontype;
zIndexNum = zIndexNum + 1;
// create the new marker data needed
var myLatLng = new google.maps.LatLng(parseFloat(latData), parseFloat(lngData));
var marker = {
position: myLatLng,
icon: gicons[icontype],
title: "",
unitIcon: unitNum,
unitLLIData: llIcon,
zIndex: zIndexNum
};
// add a line to the side_bar html
// side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '<\/a><br />';
// add an event listeners on the marker
addInfoWindow(marker, minfo);
// save the current data for later comparison
markerInfo.push(minfo);
newMarkers.push(marker);
}
// now loop thru the old marker data and compare to the new, to see if we need to remove any old markers
var refreshIt = true;
var removeIt = true;
var currNumber = "";
var currLLIcon = "";
var lastNumber = "";
var lastLLIcon = "";
for (var i = 0; i < newMarkers.length; i++) {
currNumber = newMarkers[i].unitIcon;
currLLIcon = newMarkers[i].unitLLIData;
for (var j = 0; j < oldMarkers.length; j++) {
refreshIt = true;
lastNumber = oldMarkers[j].unitIcon;
lastLLIcon = oldMarkers[j].unitLLIData;
if (lastNumber == currNumber) {
if (currLLIcon == lastLLIcon) {
refreshIt = false;
} else {
refreshIt = true;
remMarkers.push(oldMarkers[j]);
}
break;
}
}
// if we need to refresh a marker, add it to our new array here
if (refreshIt == true) {
addMarkers.push(newMarkers[i]);
}
}
// then loop thru and see if any units are no longer on the map
for (var j = 0; j < oldMarkers.length; j++) {
removeIt = true;
lastNumber = oldMarkers[j].unitIcon;
for (var i = 0; i < newMarkers.length; i++) {
currNumber = newMarkers[i].unitIcon;
if (lastNumber == currNumber) {
removeIt = false;
break;
}
}
// if we need to refresh a marker, add it to our new array here
if (removeIt == true) {
remMarkers.push(oldMarkers[j]);
}
}
// now loop thru the old markers and remove them
for (var i = 0; i < remMarkers.length; i++) {
var marker = new google.maps.Marker(remMarkers[i]);
marker.setMap(null);
side_bar_html += 'removing ' + remMarkers[i].unitIcon + '<br />';
}
// then loop thru the new markers and add them
for (var i = 0; i < addMarkers.length; i++) {
var marker = new google.maps.Marker(addMarkers[i]);
marker.setMap(map);
side_bar_html += 'adding ' + addMarkers[i].unitIcon + '<br />';
}
// and last save the old markers array into oldMarkers
oldMarkers = [];
for (var i = 0; i < newMarkers.length; i++) {
oldMarkers.push(newMarkers[i]);
}
// put the assembled side_bar_html contents into the side_bar div, then sleep
document.getElementById("side_bar").innerHTML = side_bar_html;
setTimeout('getMarkers()', 5000);
}
For context purposes, here is the code that does clear the old markers, but many (not all) or the markers blink when refreshed, even if they don't in fact move loaction.
function getMarkers() {
// create a new connection to get our xml data
var Connect = new XMLHttpRequest();
// send the get request
Connect.open("GET", xml_file, false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
// Place the response in an XML document.
var xmlDoc = Connect.responseXML;
// obtain the array of markers and loop through it
var marker_data = xmlDoc.documentElement.getElementsByTagName("marker");
// hide the info window, otherwise it still stays open where the removed marker used to be
infowindow.close();
// now remove the old markers
for (var i = 0; i < oldMarkers.length; i++) {
oldMarkers[i].setMap(null);
}
oldMarkers.length = 0;
// reset the side_bar and clear the arrays
side_bar_html = "";
markerInfo = [];
newMarkers = [];
// obtain the attributes of each marker
for (var i = 0; i < marker_data.length; i++) {
var latData = marker_data[i].getAttribute("lat");
var lngData = marker_data[i].getAttribute("lng");
var minfo = marker_data[i].getAttribute("html");
var name = marker_data[i].getAttribute("label");
var icontype = marker_data[i].getAttribute("icontype");
var unitNum = marker_data[i].getAttribute("unitNum");
zIndexNum = zIndexNum + 1;
// create the new marker data needed
var myLatLng = new google.maps.LatLng(parseFloat(latData), parseFloat(lngData));
var marker = new google.maps.Marker({
position: myLatLng,
icon: gicons[icontype],
title: "",
unitIcon: unitNum,
zIndex: zIndexNum
});
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '<\/a><br />';
// add an event listeners on the marker
addInfoWindow(marker, minfo);
// save the current data for later comparison
markerInfo.push(minfo);
newMarkers.push(marker);
oldMarkers.push(marker);
}
// now add the new markers
for (var i = 0; i < newMarkers.length; i++) {
newMarkers[i].setMap(map);
}
// put the assembled side_bar_html contents into the side_bar div, then sleep
document.getElementById("side_bar").innerHTML = side_bar_html;
setTimeout('getMarkers()', 5000);
}

Finally figured out the solution. The process was reading in new xml data which was compared to the saved xml data, to determine if a marker needed to be moved or displayed in a different color on the map.
When I created a new marker object, I did not set the map: property, because I needed to compare the lat/lon/color of the new object to the old before I determined whether a marker needed to be moved. The problem was the map: property not being set. I save the marker data without the map: property set into the new marker array, then copied the new marker array into old marker array to do the next comparison. I should have copied the old marker object into the new marker array! The old marker object HAD the map: property set, and that allowed the Google mapping code to know which marker I wanted to remove.
Sorry for the stupid mistake, but I'm pretty new to Javascript.
Rich

Related

iterate arrays with forEach Loop

in this project there are 3 files, index.html, helper.js and resumeBuilder.js. The last one is the file I work with all the time.
My problem in this project is that I can't figure how to make images array,which is inside the projects array to display in my Resume, and the same for the onLineCourses array which is inside the schools array. This online school needs to make all arrays with
forEach loop. please if someone can help to write the code I have to write to make it display, I am searching for a week and can't figure it out!
resumeBuilder.js
var projects = {
"projects" : [
{
"title":"",
"location":"",
"dates":"",
"description":"",
},
{
"title":"",
"location":"",
"dates":"",
"description":"",
>
> "images":["", ""]
}
],
};
//projects function
projects.display = function(){
$.each(projects.projects, function(i){
$("#projects").append(HTMLprojectStart);
var myProjects = projects.projects[i];
var formattedTitle = HTMLprojectTitle.replace("%data%", myProjects.title);
$(".project-entry:last").append(formattedTitle);
var formattedDates = HTMLprojectDates.replace("%data%", myProjects.dates);
$(".project-entry:last").append(formattedDates);
var formattedDescription = HTMLprojectDescription.replace("%data%", myProjects.description);
$(".project-entry:last").append(formattedDescription);
> //image array here!
> var formattedImage = HTMLprojectImage.replace("%data%",projects.images);
> $("#projects").append(HTMLprojectStart);
> $(".project-entry:last").append(formattedImage);
});
};
projects.display();
> var education = {
"schools": [
{
"name" : "",
"location" : "",
"degree":",
"majors":["","",""],
"dates" : "2",
"url" : ""
},
{
"name" : "",
"location" :"",
"degree":"",
"majors":[""],
"dates" : "",
"url" : ""
}
],
//create onLine Courses
> "onlineCourses" : [
> {
> "title" : "",
> "school" : "",
> "dates" : "",
> "url" : ""
> } ] };
//education function
education.display = function(){
$.each(education.schools, function(i) {
var mySchools = education.schools[i];
$("#education").append(HTMLschoolStart);
var formattedName = HTMLschoolName.replace("%data%",mySchools.name);
var formattedDegree = HTMLschoolDegree.replace("%data%",mySchools.degree);
var formattedNameDegree = formattedName + formattedDegree;
$(".education-entry:last").append(formattedNameDegree);
var formattedDates = HTMLschoolDates.replace("%data%",mySchools.dates);
$(".education-entry:last").append(formattedDates);
var formattedLocation = HTMLschoolLocation.replace("%data%",mySchools.location);
$(".education-entry:last").append(formattedLocation);
var formattedMajor = HTMLschoolMajor.replace("%data%",mySchools.majors);
$(".education-entry:last").append(formattedMajor);
});
//onLine courses here
> $("#education").append(HTMLonlineClasses);
> $("#education").append(HTMLschoolStart); var courses =
> education.onlineCourses; var formattedTitle =
> HTMLonlineTitle.replace("%data%", courses.title); var
> formattedSchool = HTMLonlineSchool.replace("%data%",courses.name);
> var formattedDates = HTMLonlineDates.replace("%data%", courses.dates);
> var formattedOnline = formattedTitle + formattedSchool +
> formattedDates;
> $(".education-entry:last").append(formattedOnline);
>
> };
>
> education.display();
helper.js
> /*
This file contains all of the code running in the background that makes resumeBuilder.js possible. We call these helper functions because they support your code in this course.
Don't worry, you'll learn what's going on in this file throughout the course. You won't need to make any changes to it until you start experimenting with inserting a Google Map in Problem Set 3.
/*
These are HTML strings. As part of the course, you'll be using JavaScript functions
replace the %data% placeholder text you see in them.
*/
var HTMLheaderName = '<h1 id="name">%data%</h1>';
var HTMLheaderRole = '<span>%data%</span><hr>';
var HTMLcontactGeneric = '<li class="flex-item"><span class="orange-text">%contact%</span><span class="white-text">%data%</span></li>';
var HTMLmobile = '<li class="flex-item"><span class="orange-text">mobile</span><span class="white-text">%data%</span></li>';
var HTMLemail = '<li class="flex-item"><span class="orange-text">email</span><span class="white-text">%data%</span></li>';
var HTMLtwitter = '<li class="flex-item"><span class="orange-text">twitter</span><span class="white-text">%data%</span></li>';
var HTMLgithub = '<li class="flex-item"><span class="orange-text">github</span><span class="white-text">%data%</span></li>';
var HTMLblog = '<li class="flex-item"><span class="orange-text">blog</span><span class="white-text">%data%</span></li>';
var HTMLlocation = '<li class="flex-item"><span class="orange-text">location</span><span class="white-text">%data%</span></li>';
var HTMLbioPic = '<img src="%data%" class="biopic">';
var HTMLwelcomeMsg = '<span class="welcome-message">%data%</span>';
var HTMLskillsStart = '<h3 id="skills-h3">Skills at a Glance:</h3><ul id="skills" class="flex-column"></ul>';
var HTMLskills = '<li class="flex-item"><span class="white-text">%data%</span></li>';
var HTMLworkStart = '<div class="work-entry"></div>';
var HTMLworkEmployer = '<a href="#">%data%';
var HTMLworkTitle = ' - %data%</a>';
var HTMLworkDates = '<div class="date-text">%data%</div>';
var HTMLworkLocation = '<div class="location-text">%data%</div>';
var HTMLworkDescription = '<p><br>%data%</p>';
var HTMLprojectStart = '<div class="project-entry"></div>';
var HTMLprojectTitle = '%data%';
var HTMLprojectDates = '<div class="date-text">%data%</div>';
var HTMLprojectDescription = '<p><br>%data%</p>';
var HTMLprojectImage = '<img src="%data%">';
var HTMLschoolStart = '<div class="education-entry"></div>';
var HTMLschoolName = '<a href="#">%data%';
var HTMLschoolDegree = ' -- %data%</a>';
var HTMLschoolDates = '<div class="date-text">%data%</div>';
var HTMLschoolLocation = '<div class="location-text">%data%</div>';
var HTMLschoolMajor = '<em><br>Major: %data%</em>';
var HTMLonlineClasses = '<h3>Online Classes</h3>';
var HTMLonlineTitle = '<a href="#">%data%';
var HTMLonlineSchool = ' - %data%</a>';
var HTMLonlineDates = '<div class="date-text">%data%</div>';
var HTMLonlineURL = '<br>%data%';
var internationalizeButton = '<button>Internationalize</button>';
var googleMap = '<div id="map"></div>';
$(document).ready(function() {
$('button').click(function() {
var $name = $('#name');
var iName = inName($name.text()) || function(){};
$name.html(iName);
});
});
/*
The next few lines about clicks are for the Collecting Click Locations quiz in the lesson Flow Control from JavaScript Basics.
*/
var clickLocations = [];
function logClicks(x,y) {
clickLocations.push(
{
x: x,
y: y
}
);
console.log('x location: ' + x + '; y location: ' + y);
}
$(document).click(function(loc) {
// your code goes here!
});
var map; // declares a global map variable
/*
Start here! initializeMap() is called when page is loaded.
*/
function initializeMap() {
var locations;
var mapOptions = {
disableDefaultUI: true
};
/*
For the map to be displayed, the googleMap var must be
appended to #mapDiv in resumeBuilder.js.
*/
map = new google.maps.Map(document.querySelector('#map'), mapOptions);
/*
locationFinder() returns an array of every location string from the JSONs
written for bio, education, and work.
*/
function locationFinder() {
// initializes an empty array
var locations = [];
// adds the single location property from bio to the locations array
locations.push(bio.contacts.location);
// iterates through school locations and appends each location to
// the locations array. Note that forEach is used for array iteration
// as described in the Udacity FEND Style Guide:
// https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop
education.schools.forEach(function(school){
locations.push(school.location);
});
// iterates through work locations and appends each location to
// the locations array. Note that forEach is used for array iteration
// as described in the Udacity FEND Style Guide:
// https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop
work.jobs.forEach(function(job){
locations.push(job.location);
});
return locations;
}
/*
createMapMarker(placeData) reads Google Places search results to create map pins.
placeData is the object returned from search results containing information
about a single location.
*/
function createMapMarker(placeData) {
// The next lines save location data from the search result object to local variables
var lat = placeData.geometry.location.lat(); // latitude from the place service
var lon = placeData.geometry.location.lng(); // longitude from the place service
var name = placeData.formatted_address; // name of the place from the place service
var bounds = window.mapBounds; // current boundaries of the map window
// marker is an object with additional data about the pin for a single location
var marker = new google.maps.Marker({
map: map,
position: placeData.geometry.location,
title: name
});
// infoWindows are the little helper windows that open when you click
// or hover over a pin on a map. They usually contain more information
// about a location.
var infoWindow = new google.maps.InfoWindow({
content: name
});
// hmmmm, I wonder what this is about...
google.maps.event.addListener(marker, 'click', function() {
// your code goes here!
//quiz 4 lesson 6
infowindow.open(map, marker);
});
// this is where the pin actually gets added to the map.
// bounds.extend() takes in a map location object
bounds.extend(new google.maps.LatLng(lat, lon));
// fit the map to the new marker
map.fitBounds(bounds);
// center the map
map.setCenter(bounds.getCenter());
}
/*
callback(results, status) makes sure the search returned results for a location.
If so, it creates a new map marker for that location.
*/
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
createMapMarker(results[0]);
}
}
/*
pinPoster(locations) takes in the array of locations created by locationFinder()
and fires off Google place searches for each location
*/
function pinPoster(locations) {
// creates a Google place search service object. PlacesService does the work of
// actually searching for location data.
var service = new google.maps.places.PlacesService(map);
// Iterates through the array of locations, creates a search object for each location
locations.forEach(function(place){
// the search request object
var request = {
query: place
};
// Actually searches the Google Maps API for location data and runs the callback
// function with the search results after each search.
service.textSearch(request, callback);
});
}
// Sets the boundaries of the map based on pin locations
window.mapBounds = new google.maps.LatLngBounds();
// locations is an array of location strings returned from locationFinder()
locations = locationFinder();
// pinPoster(locations) creates pins on the map for each location in
// the locations array
pinPoster(locations);
}
/*
Uncomment the code below when you're ready to implement a Google Map!
*/
// Calls the initializeMap() function when the page loads
window.addEventListener('load', initializeMap);
// Vanilla JS way to listen for resizing of the window
// and adjust map bounds
window.addEventListener('resize', function(e) {
//Make sure the map bounds get updated on page resize
map.fitBounds(mapBounds);
});

why are my google maps event listeners not working properly?

I'm trying to handle mouse over listener for each marker(there are 30 markers) and to show infowindows for these markers. I created listeners for each markers but when my mouse over the some marker it shows always the last marker's infowindows. To sum up I can't listen other markers. any help would be appreciated. thanks in advance and here my code :
var listeners = [];
for(var i = 0; i < markers.length; i++){
var marker = markers[i];
var contentString = contents[i];
listeners[i] = new google.maps.event.addListener(marker, 'mouseover', function() {
var hideInfoWindows = function(){
for (var j = 0; j < util.Common.infowindows.length; j++) {
util.Common.infowindows[j].close();
}
}
var addInfoWindow = function(){
var infowindow = new google.maps.InfoWindow({
content: contentString
});
//hideInfoWindows();
util.Common.infowindows.push(infowindow);
infowindow.open(util.Common.googlemap,marker);
}
addInfoWindow();
});
}
I'm also using js cluster library but I don't think the problem is related with it.
I think your problem might be that you are not using a closure inside the cycle, and when the event listener is fired, the marker and the contentString variables are pointing to the last marker.
Try to rewrite the cycle like this:
var listeners = [];
for(var i = 0; i < markers.length; i++){
(function(index){ //create a closure, variable 'index' will take its value from variable i, but won't be affected by changed i in the outer scope
var marker = markers[index]; //use this scope's index variable instead of i
var contentString = contents[index]; //use this scope's index variable instead of i
listeners[index] = new google.maps.event.addListener(marker, 'mouseover', function() {
var hideInfoWindows = function(){
for (var j = 0; j < util.Common.infowindows.length; j++) {
util.Common.infowindows[j].close();
}
};
var addInfoWindow = function(){
var infowindow = new google.maps.InfoWindow({
content: contentString
});
//hideInfoWindows();
util.Common.infowindows.push(infowindow);
infowindow.open(util.Common.googlemap,marker);
};
addInfoWindow();
});
})(i);
}

How to delete a direction markers in google map API

I want to delete a google map direction markers after a search without reloading the page. I've made an example but its not working :
//First of all testing if there is already a direction on the map
if(directionsService != null)
{
directionsService.setMap(null);
directionsService = null;
}
//Then display the new one
var origin = $('#de').val();
var destination = $('#en').val();
var request = {
origin : origin,
destination : destination,
travelMode : google.maps.DirectionsTravelMode.DRIVING
}
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status){
if(status == google.maps.DirectionsStatus.OK){
direction.setDirections(response);
showSteps(response);
}
});
all this code is on a function called by a click event
<button id="envoyer" id=="env" onclick="javascript:c()">Send</button>
so any one have an idea thanks !
Update
function showSteps(directionResult) {
var markerArray = [];
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_location,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
}
When clearing the itinerary, using directionsService.setMap(null); you will have to remove the MapMarkers, which aren't directly connected to the Direction - Service, seperately too.
You have already stored them in markerArray inside of your showSteps - function, so you would need to move this variable out of the function into an outer scope or let the function return it to be able to access it.
By doing this, you can simply loop over the markerArray and call .setMap(null) on each stored Marker, thus removing them from the map.
var markerArray = [];
function showSteps(directionResult){
// your code
}
//function to remove MapMarkers
function removeMapMarkers(){
for(var i=0; i<markerArray.length; i+=1){
markerArray[i].setMap(null)
}
markerArray = [];
}

If data is null, dont show

This is my code. I get the data from xml. What I want is:
if a piece of data is null, don't show that row. How can I do it?
downloadUrl("xml/cat.xml", function(doc) {
var xml = xmlParse(doc);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var kWa = markers[i].getAttribute("kWa");
var html = 'rows here ';
Sorry for wrong question..
i want to hide here
var html = '
id='+id+', kwa='+kwa+' // if id is null how can hide item in here..?
';
You can do this with if checks like:
if(markers[i].getAttribute("lat") != NULL) // or "NULL" as a string if thats what is returned."
var lat = parseFloat(markers[i].getAttribute("lat));
Or you could put it in a try - catch statement:
for (//codes){
try{
//try parsing here
}catch(e){
if(e) // do something with the error
}
Which has the advantage of letting you do something for each error message. But the disadvantage of being slow. (though not as slow as it used to be in javascript)

Getting value of "i" from GEvent

I'm trying to add an event listener to each icon on the map when it's pressed. I'm storing the information in the database and the value that I'm wanting to retrive is "i" however when I output "i", I get it's last value which is 5 (there are 6 objects being drawn onto the map)
Below is the code, what would be the best way to get the value of i, and not the object itself.
var drawLotLoc = function(id) {
var lotLoc = new GIcon(G_DEFAULT_ICON); // create icon object
lotLoc.image = url+"images/markers/lotLocation.gif"; // set the icon image
lotLoc.shadow = ""; // no shadow
lotLoc.iconSize = new GSize(24, 24); // set the size
var markerOptions = { icon: lotLoc };
$.post(opts.postScript, {action: 'drawlotLoc', id: id}, function(data) {
var markers = new Array();
// lotLoc[x].description
// lotLoc[x].lat
// lotLoc[x].lng
// lotLoc[x].nighbourhood
// lotLoc[x].lot
var lotLoc = $.evalJSON(data);
for(var i=0; i<lotLoc.length; i++) {
var spLat = parseFloat(lotLoc[i].lat);
var spLng = parseFloat(lotLoc[i].lng);
var latlng = new GLatLng(spLat, spLng)
markers[i] = new GMarker(latlng, markerOptions);
myMap.addOverlay(markers[i]);
GEvent.addListener(markers[i], "click", function() {
console.log(i); // returning 5 in all cases.
// I _need_ this to be unique to the object being clicked.
console.log(this);
});
}
});
You have an issue with closures. Your functions see i's last valuse. Simply add another closure to fix your error:
for(var i=0; i<lotLoc.length; i++) {
(function(i){
// ...
})(i); //run the function with i as argument
}//for

Categories

Resources