Google map is taking too long to load - google-maps

I am opening a google map on page load and add pointers to it on the basis of data fetched from the database. But the problem here is it takes approx 3-4 minutes to load, cpu utilization reaches to 100% and RAM is also consumed a lot. Below is the code:
<div class="col-md-12">
<div class="row">
<div class="col-md-10">
<div id="map" style='height: 85vh;'></div>
</div>
</div>
</div>
<script>
var infowindows = [];
var notification_location, cirle_area_for_notification = null;
function initMap() {
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
// center: {lat: markers[0].lat, lng: markers[0].lng},
center: {lat: -33.826668, lng: 151.231526},
type:['(regions)'],
componentRestrictions: {
country: ['aus']
}
});
var icon, content = '';
<% #users.find_in_batches(batch_size: 200) do |users| %>
<% users.each do |user| %>
<% if user.staff? %>
icon = "<%= image_url 'blue.svg' %>";
content = ''
+ 'Name: <b></b></br>'
+ 'Role: <b>staff</b></br>'
+ 'Phone Number: <b><%= user.phone_number %></b></br>'
+ 'Qualification: <b><%= user.qualification_levels&.last&.name %></b></br>'
+ 'Radius: <b><%= user.address.radius %></b></br>'
+ 'Centers in same zone: <b><%= user.staff_active_centers_in_same_zones.pluck(:user_id) %></b></br>';
<% else %>
icon = "<%= image_url 'orange.svg' %>";
content = ''
+ 'Name: <b><%= user.user_name %></b></br>'
+ 'Role: <b>center</b></br>'
+ 'Phone Number: <b><%= user.phone_number %></b></br>'
+ 'Staffs in same zone: <b><%= user.center_active_staffs_in_same_zones.size %></b></br>';
<% end %>
var infowindow = new google.maps.InfoWindow({
content: content
});
infowindows.push(infowindow);
var marker = new google.maps.Marker(
{
position: {lat: <%= user.address.latitude %>, lng: <%= user.address.longitude %>},
map: map,
title: '<%= user.user_name %>',
animation: google.maps.Animation.DROP,
icon: new google.maps.MarkerImage(icon),
id: '<%= user.id %>',
users_in_same_zone: '<%= user.center_active_staffs_in_same_zones.pluck(:staff_user_id) %>'
}
);
//Click event on marker
marker.addListener('click', function() {
close_map_info_windows();
infowindow.open(map, marker);
});
<% end %>
<% end %>
// Close map infowindow
function close_map_info_windows(){
for (var i = 0; i < infowindows.length; i++) {
infowindows[i].close();
}
}
</script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=<%= Rails.application.secrets.google_api_key %>&libraries=places&callback=initMap">
</script>
Below is the controller code
#users = User.active.accepted.joins(:address)
.includes(:address, :qualification_levels, :staff_profile, :center_profile, :center_active_staffs_in_same_zones, :staff_active_centers_in_same_zones)
If I increase the batchsize more than 200, the response time increases. I am looping in view because I need to assign the values to the javascript functions
I am using RAILS5.
Any suggestions to optimize this page?

As first thing, it looks like you're having a N+1 issue.
Try adding .includes for models like staff_profile, qualification_levels, address or staff_active_centers_in_same_zones for your users query.
Something that could help you to identify those models is the bullet gem.
In any case, your code smells like something could be wrong as you potentially could load more than 200 user points in the map (telling because of the batch_size: 200 in your query), but only you know what should be doing your page.
And unrelated, but also move the query logic to the controller. In the view looks the wrong place to call it using a MVC approach.

Related

Printing page with multiple embedded Google Maps in WebKit produces tile errors

Printing the following example page in either Chrome or Safari on Mac (i.e., WebKit) produces misplaced map tiles in the printed output from the second map onwards. It works on the webpage itself, and printing it does also seem to work in Firefox. Need it to work in Chrome or Safari, though.
Example page: http://matsch.binaervarianz.de/tmp/print_entries.html
Print-to-PDF output of the page: http://matsch.binaervarianz.de/tmp/print_entries.pdf
(See, e.g., the displacement of road US421 on page 2 onwards.)
It looks like a caching problem that only affects printing. But clearing the cache or private/incognito browsing doesn't solve the issue.
While in the example all map sections are the same are, the problem also occurs with different maps (e.g., try panning and zooming in the example).
I'm OK with a partial solution where I can get it to work in my own browser -- i.e., it does not have to work for everyone, but it must be Webkit (Safari or Chrome). Can't use Firefox for this...
Bonus points if this works for everyone.
Here is some code how maps are initialized. More in the example page above.
// first map
var snippets = [];
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510463",
snippet_location_long: "-86.2288448"
});
var mapData_2899_1 = {
snippets: snippets,
entry_approx_location_lat: "",
entry_approx_location_long: ""
};
showMap(mapData_2899_1, "2899_1");
// second map
snippets = [];
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510639",
snippet_location_long: "-86.2287998"
});
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510739",
snippet_location_long: "-86.2288998"
});
var mapData_2899_3 = {
snippets: snippets,
entry_approx_location_lat: "",
entry_approx_location_long: ""
};
showMap(mapData_2899_3, "2899_3");
// show map function
function showMap(d, primKey) {
$( '#map-' + primKey ).addClass('map-canvas');
var mapOptions = {
center: { lat: 39.9513164, lng: -86.2274201 },
streetViewControl: false, zoom: 12,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById('map-' + primKey), mapOptions);
$.each(d.snippets, function( i, snippet ) {
// location when snippet was recorded
if (snippet.snippet_location_lat !== "" && snippet.snippet_location_long !== "") {
var snippetLoc = new google.maps.LatLng(
p(snippet.snippet_location_lat),
p(snippet.snippet_location_long)
);
var marker = new google.maps.Marker({ position: snippetLoc, map: map });
}
// approximate location taking into account how long ago the event reportadly took place
if (snippet.snippet_approx_location_lat !== "") {
var snippetApproxLocation = new google.maps.LatLng(
p(snippet.snippet_approx_location_lat),
p(snippet.snippet_approx_location_long)
);
var marker2 = new google.maps.Marker({
position: snippetApproxLocation,
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
}
});
// approximate location at corrected time from diary entry
if (d.entry_approx_location_lat !== "") {
var entryApproxLocation = new google.maps.LatLng(
p(d.entry_approx_location_lat),
p(d.entry_approx_location_long)
);
var marker3 = new google.maps.Marker({
position: entryApproxLocation,
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/yellow-dot.png'
});
}
}
function p( string ) {
if (string === null)
return "";
else
return string;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDO_bHfTaLLr2Ugghz1hQ2QIZdRaa0SKX0"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<style type="text/css">
.map-canvas {
width: 325px;
height: 325px;
float: right;
margin: 5px;
}
</style>
<div id="map-2899_1" class="map-canvas"></div><br><br>
<div id="map-2899_3" class="map-canvas"></div>
I found workaround for what I think is a bug in WebKit. Since caching of map tiles didn't seem to be the problem, I started playing around with CSS display and position properties.
Adding display:inline-block; to my .map_canvas seems to solve the problems in the printout… The tiles are now all correct. display:inline; alone doesn't have the same effect; and I don't know why inline-block solves the problem.
(Since in my particular case I wanted the map to float:right; I had to put a wrapper around the .map_canvas div. So, .map_canvas has the display:inline-block; and the .map-container has float:right;.)
So, it seems, in WebKit, print support for multiple maps on a page is either buggy, or I'm not understanding it fully.
Here, now, is the working example page: http://matsch.binaervarianz.de/tmp/print_entries-solution.html
And this is the Print-to-PDF output of that page: http://matsch.binaervarianz.de/tmp/print_entries-solution.pdf
Here's the working code (only the HTML/CSS has changed):
// first map
var snippets = [];
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510463",
snippet_location_long: "-86.2288448"
});
var mapData_2899_1 = {
snippets: snippets,
entry_approx_location_lat: "",
entry_approx_location_long: ""
};
showMap(mapData_2899_1, "2899_1");
// second map
snippets = [];
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510639",
snippet_location_long: "-86.2287998"
});
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510739",
snippet_location_long: "-86.2288998"
});
var mapData_2899_3 = {
snippets: snippets,
entry_approx_location_lat: "",
entry_approx_location_long: ""
};
showMap(mapData_2899_3, "2899_3");
// show map function
function showMap(d, primKey) {
$( '#map-' + primKey ).addClass('map-canvas');
var mapOptions = {
center: { lat: 39.9513164, lng: -86.2274201 },
streetViewControl: false, zoom: 12,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById('map-' + primKey), mapOptions);
$.each(d.snippets, function( i, snippet ) {
// location when snippet was recorded
if (snippet.snippet_location_lat !== "" && snippet.snippet_location_long !== "") {
var snippetLoc = new google.maps.LatLng(
p(snippet.snippet_location_lat),
p(snippet.snippet_location_long)
);
var marker = new google.maps.Marker({ position: snippetLoc, map: map });
}
// approximate location taking into account how long ago the event reportedly took place
if (snippet.snippet_approx_location_lat !== "") {
var snippetApproxLocation = new google.maps.LatLng(
p(snippet.snippet_approx_location_lat),
p(snippet.snippet_approx_location_long)
);
var marker2 = new google.maps.Marker({
position: snippetApproxLocation,
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
}
});
// approximate location at corrected time from diary entry
if (d.entry_approx_location_lat !== "") {
var entryApproxLocation = new google.maps.LatLng(
p(d.entry_approx_location_lat),
p(d.entry_approx_location_long)
);
var marker3 = new google.maps.Marker({
position: entryApproxLocation,
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/yellow-dot.png'
});
}
}
function p( string ) {
if (string === null)
return "";
else
return string;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDO_bHfTaLLr2Ugghz1hQ2QIZdRaa0SKX0"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<style type="text/css">
.map-container {
float: right;
margin-left: 5px;
}
.map-canvas {
width: 325px;
height: 325px;
display: inline-block;
}
</style>
<div class="map-container">
<div id="map-2899_1" class="map-canvas"></div>
</div>
<br><br>
<div class="map-container">
<div id="map-2899_3" class="map-canvas"></div>
</div>

using classic asp (obsolete I know but it is a start), how to plot multiple markers on a gmap and msaccess database

I have this code that I recycled from the internet to extract lng lat data from ms access database and plot on a Google map. The map is showing and the coordinates are their but no markers are showing. the code I use shown below. Once again thank you
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org
/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org
/1999/xhtml">
<head>
<script src="http://maps.google.com
/maps/apijs?key=AIzaSyCnkGeTzGO1_5_mCfAJZkQmG6RZOkyjGzE& sensor=false"
type="text/javascript">
</script>
</head> <body> <div id="map" style="width: 750px; height: 550px"></div>
<% # Language="VBScript" %>
<%
Dim count, DataConn, rst, cmdTemp
Dim lng, lat
Dim countryArr(), songTitleArr(), songFileNameArr()
Dim ptLatArr(), ptLngArr()
Dim currLng, currLat
Dim theCtr
reDim countryArr(100)
reDim songTitleArr(100)
reDim songFileNameArr(100)
reDim ptLatArr(100)
reDim ptLngArr(100)
lat=-14.7793992
lng= 121.0236486
count = 0
Set DataConn = Server.CreateObject("ADODB.Connection")
Dataconn.Provider="Microsoft.Jet.OLEDB.4.0"
DataConn.Open "D:/Webpage/data/philapig_b_V10.mdb"
Set cmdTemp = Server.CreateObject("ADODB.Command")
Set rst = Server.CreateObject("ADODB.Recordset")
cmdTemp.CommandText = "SELECT Farmer_No, Surname, Firstname, Category, YCoordinate,
XCoordinate, Type FROM FarmersDataWeb"
cmdTemp.CommandType = 1
Set cmdTemp.ActiveConnection = DataConn
rst.Open cmdTemp, , 1, 3
Do While NOT rst.EOF
countryArr(count)= rst("Farmer_No")
songTitleArr(count)= rst("Category")
songFileNameArr(count)= rst("Type")
ptLatArr(count)= rst("XCoordinate")
ptLngArr(count)= rst("YCoordinate")
rst.MoveNext()
count = count + 1
loop
rst.Close
Set rst = Nothing DataConn.Close
set DataConn = nothing %>
<script type="text/javascript" language="javascript">
var map = new google.maps.Map(document.getElementById("map"),{
zoom: 10,
center: new google.maps.LatLng(14.7793992,121.0236486),
mapTypeId: google.maps.MapTypeId.ROADMAP });
function createMarker(point,ctr) {
var theMarker = new GMarker(point);
var infoText= ctryArr[ctr] + "<BR>" + sTitleArr[ctr] + "<a href=" +
sFileNameArr[ctr] + "><BR>Listen</a>";
GEvent.addListener(theMarker, "click", function()
{theMarker.openInfoWindowHtml(infoText);});
return theMarker; }
function setMarker(ctr) {
var pt = new GPoint(lngArr[ctr], latArr[ctr]);
var marker = createMarker(pt,ctr);
map.addOverlay(marker); }
var ctryArr=[]; var lngArr=[]; var latArr=[]; var sTitleArr=[]; var sFileNameArr=[]; var
j=0;
<% for i = 0 to count - 1 %>
ctryArr[j]="<%=countryArr(i)%>";
sTitleArr[j]="<%=songTitleArr(i)%>";
sFileNameArr[j]="<%=songFileNameArr(i)%>";
lngArr[j]="<%=ptLngArr(i)%>";
latArr[j]="<%=ptLatArr(i)%>";
j++;
<% next %>
for (k=0;k<ctryArr.length;k++) {
setMarker(k); }
</script>
</body>
</html>
I changed your code to work with the V3 Google Maps API. Replace the SCRIPT part with the following code.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" language="javascript">
var map;
function initializeGoogle() {
var myOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
panControl: true,
zoomControl: true,
center: new google.maps.LatLng(14.7793992,121.0236486)
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
<% for i = 0 to count - 1 %>
createMarker(<%=ptLatArr(i)%>, <%=ptLngArr(i)%>, ctryArr[ctr] + "<BR>" + sTitleArr[ctr] + "<BR>Listen");
<% next %>
};
function createMarker(lat, lon, html) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: html
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(newmarker, 'mouseover', function() {
this['infowindow'].open(map, this);
});
}
$(document).ready(function () {
initializeGoogle();
});
</script>

gmaps4rails v2 - insert infoWindow close button INTO the infowindow

I'm using gmaps4rails to display markers on a google map.
It's working well but i can't figure out how to remove the default close button for the infowindows and insert it INTO the infowindow with the customizations of my choice.
index.html.erb:
<div class='full_height' style='width: auto;'>
<div id="map" class='full_height' style='width: 100%;'></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var raw_markers = <%=raw #hash.to_json %>;
function createSidebarLi(json){
return ("<li>" + json.titre + ' ' + json.address + "</li>");
};
function bindLiToMarker($li, marker){
$li.on('click', function(){
handler.getMap().setZoom(14);
marker.setMap(handler.getMap()); //because clusterer removes map property from marker
marker.panTo();
google.maps.event.trigger(marker.getServiceObject(), 'click');
});
};
function createSidebar(json_array){
_.each(json_array, function(json){
var $li = $( createSidebarLi(json) );
$li.appendTo('#markers_list');
bindLiToMarker($li, json.marker);
});
};
handler = Gmaps.build('Google', { builders: { Marker: InfoBoxBuilder} });
handler.buildMap({ internal: {id: 'map'}}, function(){
var markers = handler.addMarkers(raw_markers);
_.each(raw_markers, function(json, index){
var marker = markers[index];
json.marker = marker;
google.maps.event.addListener(handler.getMap(), "click", function(){
infoWindow.close();
});
google.maps.event.addListener(marker.getServiceObject(), 'mouseover', function(){
google.maps.event.trigger(marker.getServiceObject(), 'click');
});
});
createSidebar(raw_markers);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
});
</script>
infoboxBuilder.js.coffee:
class #InfoBoxBuilder extends Gmaps.Google.Builders.Marker # inherit from base builder
# override method
create_infowindow: ->
return null unless _.isString #args.infowindow
boxText = document.createElement("div")
boxText.setAttribute("class", 'yellow') #to customize
boxText.innerHTML = #args.infowindow
#infowindow = new InfoBox(#infobox(boxText))
infobox: (boxText)->
content: boxText
pixelOffset: new google.maps.Size(0, -20)
boxStyle:
width: "280px"
controller:
def index
if params[:search].present?
#properties = Property.near(params[:search], 100, )
else
#properties = Property.all
end
#hash = Gmaps4rails.build_markers(#properties) do |property, marker|
#sameLocation = #properties.near(property)
marker.lat property.latitude
marker.lng property.longitude
marker.infowindow render_to_string(:partial => "/properties/infowindow", :locals => { :property => property})
marker.json({ titre: property.titre, address: property.address})
#marker.picture({
# :url => 'http://198.100.149.26/lookn/marker.png',
# :width => 60,
# :height => 82
#})
end
end

MVC4 Knockout Googlemap binding error

I'm trying to bind an address from my model to a marker on Google map.
The map should display the marker determined with the full address of the model. Beside the map, I would like to display the value for lat and lng of the marker. The user should be able to drag and drop the marker and the values of lat & lng should update. I use jsFiddle as start referenced from this website but I cannot quite get it to work.
I successfully created the map with a marker pointing to the address of the model. Unfortunately I'm get an error when adding knockout to bind it:
Uncaught Error: Unable to parse bindings.
Message: ReferenceError: lat is not defined;
Bindings value: value: lat
This is the view:
#model GoogleMapTest.Models.Restaurant
#{
ViewBag.Title = "Index";
}
<div id="panel">
<input id="address" value="">
<p data-bind="with: selectedPoint">
Name: <b>#Model.Name</b>
<br />
Lat: <span data-bind="text: lat"></span>
<br />
Long: <span data-bind="text: long"></span>
</p>
</div>
<div id="map-canvas"></div>
This is the script:
#section scripts {
<script type="text/javascript">
var geocoder;
var map;
var orignalLat;
var originalLong;
$(function () {
var stringAddress = '#Model.Address1' + ", " + '#Model.City' + ", " + '#Model.StateProv' + ", " + '#Model.Zip' + ", " + '#Model.Country';
$("#address").val(stringAddress);
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 16
}
google.maps.event.addDomListener(window, 'load', codeAddress(stringAddress));
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
});
function codeAddress(address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
orignalLat = results[0].geometry.location.lat();
originalLong = results[0].geometry.location.lng();
map.setCenter(results[0].geometry.location);
viewModel.selectedPoint(new point('', orignalLat, originalLong));
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function point( name, lat, long) {
this.name = name;
this.lat = ko.observable(lat);
this.long = ko.observable(long);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, long),
title: name,
map: map,
draggable: true
});
//if you need the position while dragging
google.maps.event.addListener(marker, 'drag', function () {
var pos = marker.getPosition();
this.lat(pos.lat());
this.long(pos.lng());
}.bind(this));
//if you just need to update it when the user is done dragging
google.maps.event.addListener(marker, 'dragend', function () {
var pos = marker.getPosition();
this.lat(pos.lat());
this.long(pos.lng());
}.bind(this));
}
var viewModel = {
selectedPoint: ko.observable(new point('', 10, 10))
};
ko.applyBindings(viewModel);
</script>
}
Any help or suggestions would be greatly appreciated.
Edited for working solution...
Your viewModel consists of an array of points, but your markup binds directly to lat and lng properties that don't exist on the root viewModel. So that's why you are getting the error, but how to fix it is more interesting.
I'm actually not sure what you are trying to do and the fix is different based on that. Do you want ONE marker that displays when the user selects a point? Or do you want every point to have a marker on the map right from the beginning?
If you want markers for ALL points, change your markup to bind to all of them:
<p data-bind="foreach: points">
Name: <b>#Model.Name</b>
<br />
Lat: <span data-bind="text: lat"></span>
<br />
Long: <span data-bind="text: long"></span>
</p>
OR... If you want just one marker, I would first add a "selectedPoint" to your viewModel
var viewModel = {
selectedPoint: new point('', 0, 0),
points: (removed)
};
Then in your markup, bind the lat and lng on the selected point
<p data-bind="with: selectedPoint">
Name: <b>#Model.Name</b>
<br />
Lat: <span data-bind="text: lat"></span>
<br />
Long: <span data-bind="text: long"></span>
</p>

How to define dynamic variables in JSP loop?

I have written the following code to display markers and have respective info windows displaying name of the policestation.
The policestation class has name, latitude and longitude.
<script>
function initialize()
{
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var myCenter = new google.maps.LatLng(28.6523605,77.0910645);
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var mapProp = {
center: myCenter,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = [];
var info= [];
<%
ArrayList<PoliceStation> stationList = new PoliceStation().loadclass();
for (int i=0 ; i < stationList.size() ; i++) {
%>
var pos = new google.maps.LatLng(
<%= stationList.get(i).getLatitude()%>,
<%= stationList.get(i).getLongitude()%>
);
marker = new google.maps.Marker({
position: pos,
map: map
});
marker.setMap(map);
var MarkerContent = "<div class=\"marker\">" +
"<h2>"+ "<%=stationList.get(i).getstationName()%>"
+"</h2>"+
"</div>";
info=new google.maps.InfoWindow();
info.setOptions({
content: MarkerContent,
size: new google.maps.Size(50, 50),
position: pos
});
google.maps.event.addListener(marker, 'click', function () {
info.setOptions({
content: MarkerContent
});
info.open(map, marker);
});
<%
}
%>
All the markers are set as expected. However clicking any marker results in opening the infowindow of only the last marker drawn.
I get that this is because all the marker, infoWindow names are redundant and in the end only the last infoWindow gets saved to the last marker.
I have come across solutions that encapsulate the content inside the for loop with
(function() {var marker = ...; google.maps.event.addListener...;})();
However, I'm looking for a solution to dynamically distinctly define each variable name.
like for example append the value of a counter incremented at each iteration to each marker and info variable.
Kindly do not provide JSTP solution. looking for a specific JSP solution
Surprisingly it was really easy...
JSP is basically used to print HTML dynamically.
so, instead of using marker variable as
var marker = new google.maps.Marker({
position: pos,
map: map
});
use -
var <%out.print("marker"+i);%> = new google.maps.Marker({
position: pos,
map: map
});
It is to be noted that-
var <%out.print("marker["+i+"]");%> = new google.maps.Marker({
position: pos,
map: map
});
did not work for me.
The correct code above creates new variables with values marker1, marker2... etc
also the content update function inside the event listener-
info.setOptions({
content: MarkerContent
});
is not required.