I am trying to render Google map with Latitude and Longitude from my MVC Model by using different examples. Google Map is displaying fine but it is not displaying the markers. I am very new to the Google Maps and feeling completely clueless about it. Can please anyone tell me how I can get the markers?
My MVC view is as follow
if (Model.WidgetType == "Map")
{
<div class="experienceRestrictedText">
<script src="//maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var London = new google.maps.LatLng(#Html.Raw(Json.Encode(Model.UserLatitude)), #Html.Raw(Json.Encode(Model.UserLongitude)));
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 14,
center: London,
mapTypeId: google.maps.MapTypeId['ROADMAP']
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$.get("/Home/GetMapLocations", function(data){
$.each(data, function(i, item){
var marker = new google.maps.Marker({
'position' : new google.maps.LatLng(item.Latitude, item.Longitude),
'map' : map,
'title': item.EngineerName
});
});
});
#*var data = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.lstMapLocations));
$.each(data, function (i, item){
var marker = new google.maps.Marker({
'position' : new google.maps.LatLng(item.Latitude, item.Longitude),
'map' : map,
'title': item.EngineerName
});
});*#
}
</script>
<div class="map" id="map" style="width:690px; height:400px;"></div>
</div>
}
MVC Controller is as follow
public ActionResult GetMapLocations()
{
var lstMapLocations = new List<MapLocation>();
var mapLocationModel1 = new MapLocation
{
EngineerName = "Engineer1",
SiteName = "Site1",
Latitude = 51.507351,
Longitude = -0.127758,
LstDouble = new List<double>()
};
var mapLocationModel2 = new MapLocation
{
EngineerName = "Engineer2",
SiteName = "Site2",
Latitude = 51.481728,
Longitude = -0.613576,
LstDouble = new List<double>()
};
var mapLocationModel3 = new MapLocation
{
EngineerName = "Engineer3",
SiteName = "Site3",
Latitude = 51.628611,
Longitude = -0.748229,
LstDouble = new List<double>()
};
var mapLocationModel4 = new MapLocation
{
EngineerName = "Engineer4",
SiteName = "Site4",
Latitude = 51.26654,
Longitude = -1.092396,
LstDouble = new List<double>()
};
lstMapLocations.Add(mapLocationModel1);
lstMapLocations.Add(mapLocationModel2);
lstMapLocations.Add(mapLocationModel3);
lstMapLocations.Add(mapLocationModel4);
foreach(var item in lstMapLocations)
{
item.LstDouble.Add(item.Latitude);
item.LstDouble.Add(item.Longitude);
item.LatLong = item.LstDouble.ToArray();
}
return Json(lstMapLocations);
}
I have found a work around to my problem and thought to share it for those who may stumble upon a similar issue. Courtesy stack overflow post particularly the answer posted by Atish Dipongkor. There may well be a better alternative to this problem but this approach has resolve my problem. I have made little change in that answer as Atish has used apostrophes while retrieving data from model which can break the functionality if any of the model field has string data with apostrophe in it. My appended solution with the above dummy data (in my question) is as follow
<div class="experienceRestrictedText">
<script src="//maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var London = new google.maps.LatLng(#Html.Raw(Json.Encode(Model.UserLatitude)), #Html.Raw(Json.Encode(Model.UserLongitude)));
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 8,
center: London,
mapTypeId: google.maps.MapTypeId['ROADMAP']
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
#foreach (var item in Model.lstMapLocations)
{
<text>
var markerLatLong = new google.maps.LatLng(#(item.Latitude), #(item.Longitude));
var markerTitle = #Html.Raw(Json.Encode(item.EngineerName));
var markerContentString = #Html.Raw(Json.Encode(item.EngineerName)) + " At " + #Html.Raw(Json.Encode(item.SiteName));
var infowindow = new google.maps.InfoWindow({
content: markerContentString
});
var marker = new google.maps.Marker({
position: markerLatLong,
title: markerTitle,
map: map,
content: markerContentString
});
google.maps.event.addListener(marker, 'click', (function (marker) {
return function () {
infowindow.setContent(marker.content);
infowindow.open(map, marker);
}
})(marker));
</text>
}
}
</script>
<div class="map" id="map" style="width:690px; height:400px;"></div>
</div>
Related
I scraped data from Json and containing arrays in queryLat/queryLng after that I create another function initMap also bind it to google script. But I having hard to time passing queryLat and queryLng into initMap. "queryLat is not defined" pops up. How I can pass those to initMap.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var newMarker = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
For multiple markers if you are defining arrays globally then you have to push your lat and long values in array and also need to update the marker variable to display diferent markers.. Hope it helps you to get the multiple markers.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat.push(data.results[0].geometry.location.lat);
queryLng.push(data.results[0].geometry.location.lng);
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var new_marker_str = "newMarker"+i;
new_marker_str = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
You Should define your variables queryLat and queryLng globally where your script starts.
<script type="text/javascript">
var queryLat;
var queryLng;
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 12,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
var marker = new
google.maps.Marker
({
position: {lat: queryLat, lng: queryLng},
map: map
});
}
The problem is in this code:
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
You have enclosed the string with apostrophes, but the string contains apostrophes too.
Use this instead:
url: "https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}"
I try to use the Json Ajax for google map markers.So after clicking on the button run Ajax, I get a problem with it. it's not display markers
Should change be made?
Where is my problem?
this is My Action after run ajax:
[HttpPost]
public ActionResult AsMapAjax(string jobid,string subid,string Searchitem)
{
string markers = "[";
foreach (var item in UnitOfWork.WD.GetAll())
{
markers += "{";
markers += string.Format("'title': '{0}',", "Test");
markers += string.Format("'lat': '{0}',", item.Lat);
markers += string.Format("'lng': '{0}',", item.Lng);
markers += string.Format("'description': '{0}'", "www.google.com");
markers += "},";
}
markers += "];";
var mark= new MvcHtmlString(markers);
return Json(new { success = true, responseText = mark }, JsonRequestBehavior.AllowGet);
}
}
and my jquery ajax(scripts):
navigator.geolocation.getCurrentPosition(function (p) {
var latlng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var mapOptions = {
center: latlng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
//You re Here
var iconoMarca = "../../images/URHere.gif";
mymarker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
map: map,
icon: iconoMarca,
position: latlng
});
$('#prt').on('click', function () {
var Subid = document.getElementById("bluee").value;
var jobid = document.getElementById("Jobs").value;
var Searchitem = document.getElementById("SearchItem").value;
$.ajax({
type: "post",
url: "/My/AsMapAjax",
dataType: 'json',
data: { subid:Subid,jobid:jobid,Searchitem:Searchitem},
success: function (response) {
if (response != null && response.success) {
//alert(response.responseText);
markers=response.responseText;
} else {
alert("there is a problem!");
}
},
error: function (response) {
alert("Sorry!try again please.");
}
}
)
///////
//label
var numberMarkerImg = {
url: '../../images/shapemarker.png',
size: new google.maps.Size(32, 38),
scaledSize: new google.maps.Size(32, 38),
labelOrigin: new google.maps.Point(21,42)
};
var markerLabel = 'Test';
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
//label
label:markerLabel ,
title: data.title,
icon:numberMarkerImg,
animation: google.maps.Animation.DROP
});
( function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
window.location.href = "/My/sargarmi";
});
})
(marker, data);
}
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
});
but the markers not display ! how to fix this problem?
or is other way for this question?
thanks a lot
Your question does not explain what specific problem you are experiencing. So i am going to give you a simple - working solution which improves some of the stuff you did.
Let's start with your server method. You are building the stringified version of a json array by string concatenation. That is unnecessary and error prone. Why not let the JSON serializer which is part of the mvc framework to do that for you ?
Create a simple class to represent your marker
public class Marker
{
public string Title { set; get; }
public double Lat { set; get; }
public double Lng { set; get; }
}
Now in your action method, Build a list of this Marker class and you can pass that to the Json method.
[System.Web.Mvc.HttpPost]
public ActionResult AsMapAjax(string jobid, string subid, string Searchitem)
{
//Hard coded for demo. You may replace with values from db
var list = new List<Marker>
{
new Marker() { Title="AA" ,Lat = -33.890542, Lng=151.274856 },
new Marker() { Title="BB", Lat = -33.923036, Lng=151.259052 },
new Marker() { Title="CC" ,Lat = -34.028249, Lng=151.157507 },
};
return Json(new { success = true, responseText = list });
}
Now in your client side, you make the ajax call to this action method, read the response coming back and add markers.
$(function() {
$('#prt').on('click', function() {
initMap();
});
});
function initMap() {
//read the parameter values you want to send to server
var searchItem =$("#SearchItem").val();
var jobs=$("#Jobs").val();
var subid = $("#bluee").val();
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 8
});
var url = "#Url.Action("AsMapAjax", "Home")";
$.post(url, { searchTerm: searchItem,jobid: jobs,subid : subid },function(res) {
if (res.success) {
var latLng;
$.each(res.responseText,function(i, item) {
latLng = new google.maps.LatLng(item.Lat, item.Lng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
});
map.setCenter(latLng);
}
});
}
I am using the Url.Action method to generate the correct relative url to the action method as my script was inside a razor code block. If you are using this code in an external javascript file, follow the solution described in this post to handle that case
I'm starting to learn Google Map. It's strange that when statically declared, markers are working and being displayed, but when they come from DB, they aren't being drawn on map.
// var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.692186, 'Device 2'], [15.033303, 120.694611, 'Device 3']];
var markers = [];
I have the entire code here, maybe I am missing something? I even used console log and I successfully pass all data from ajax to markers variable.
I think I got this code somewhere here in SO and modified it to fit in for my DB calls for records. I hope you can help me out on this one. Thank you!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script type="text/javascript">
var map;
var global_markers = [];
// var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.692186, 'Device 2'], [15.033303, 120.694611, 'Device 3']];
var markers = [];
var infowindow = new google.maps.InfoWindow({});
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(15.058607, 120.660884);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$.ajax({
type: 'GET',
url: 'control_panel/get_device_list_ajax',
success:
function (data) {
data = JSON.parse(data);
if (data['success']){
var device = data['device_list'];
device.forEach(function (dev) {
markers.push([dev['dev_geolat'], dev['dev_geolng'], dev['dev_name']]);
//console.log(markers);
});
addMarker();
} else {
}
}
});
}
function addMarker() {
console.log(markers);
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var trailhead_name = markers[i][2];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " | Trailhead name: " + trailhead_name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
window.onload = initialize;
</script>
EDIT
Here is the jsfiddle I used to work with this one http://jsfiddle.net/kjy112/ZLuTg/ (thank you to the one that lead me to this)
Could be related to the way you accessing to json rendered by ajax
markers.push([dev.dev_geolat, dev.dev_geolng, dev.dev_name]);
or the json content
I don't know how to close this question as I overlooked some problems on my DB but I'll be posting my answer if someone may come with the same problem (well, I am not sure about that hehe)
I get the same response from AJAX of the values in DB and I am not able to draw markers on MAP, I found that db->table->fields LAT LNG are referenced with a data type of DECIMAL (7,5) and changed it to FLOAT (10, 6) as to what is found in this GOOGLE MAP Tutorial - Using PHP/MySQL with Google Maps.
The issue at the field before was that higher values tend to be saved as 99.999999 instead of the actual value (e.g. 120.XXXXX) .
I have implemented Google Maps JavaScript API v3 to contrive a custom store locator for my company's website. Let me start by saying that the code I have works for the two stores, but it would not be efficient or feasible if I added any more stores because of the "hacky" code used to make it work.
I am using the Google Maps Places Library to send "place details" requests to Google using the getDetails() method. On the callback, I am receiving the InfoWindow information (name, address, location) for each of my store locations.
I create a marker for each place, then use google.maps.event.addListener to coordinate the Place, Marker, and InfoWindow objects. This is where I encounter problems. The place details requests are not always received in the same order they are sent which throws off the indexing of my buttons that have a data-marker attribute set to 0 and 1, respectively, to correlate to the map markers.
Is there anyway to delay the second request until the first is finished? or write the script in a way that maintains ordinal integrity?
The first snippet of code below is my event handler to bind the click listener to each button using the .place.placeId property of the marker rather than the preferred technique of using the index of the markers array (the markers array holds the place details for the two stores).
None of the demos or examples in the Google Maps API documentation (Places Library) delineate the procedure for multiple places. Any tips, resources, or suggestions will be much appreciated
Website: http://m.alliancepointe.com/locate.html
Event Handler
$(".loc-btn").on('click', function () {
var me = $(this).data('marker');
var place1 = markers[0].place.placeId;
var myIndex = me == place1 ? 0 : 1;
google.maps.event.trigger(markers[myIndex], 'click');
});
Full JS
var markers = [];
var map;
var infowindow;
var service;
function initialize() {
var index;
var daddr;
var idVA = 'ChIJKezXgqmxt4kRXrAnqIwIutA';
var geoVA = '38.80407,-77.062881/Alliance+Pointe,+LLC';
var idDC = 'ChIJDQlqOLG3t4kRqDU3uNoy4hs';
var geoDC = '38.90188,-77.049161/Alliance+Pointe,+LLC';
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
center: {lat: 38.90188, lng: -77.049161},
zoom: 10,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var request = [
{placeId: idVA, location: {lat: 38.80407, lng: -77.062881}},
{placeId: idDC, location: {lat: 38.90188, lng: -77.049161}}
];
var office = [
"Main Office",
"Principal Office"
];
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
for (var i = 0; i < request.length; i++) {
service.getDetails(request[i], function (placeResult, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var id = placeResult.place_id;
var location = placeResult.geometry.location;
var trimAddr = placeResult.formatted_address.split(", ");
var image = {
url: 'images/icons/AP-marker_large.png',
scaledSize: new google.maps.Size(32, 54)
};
var marker = new google.maps.Marker({
map: map,
place: {
placeId: id,
location: location
},
icon: image,
title: "Get directions"
});
google.maps.event.addListener(marker, 'click', function () {
if (id == idVA) {
index = 0;
daddr = geoVA;
trimAddr[0] = "1940 Duke St #200";
} else {
index = 1;
daddr = geoDC;
trimAddr[0] = "2200 Pennsylvannia Ave NW";
}
infowindow.setContent('<div class="info-window title">' + placeResult.name + "</div><div class='info-window sub-title'>" + office[index] + '</div><div class="info-window">' + trimAddr[0] + '<br>' + trimAddr[1] + ", " + trimAddr[2] + '</div><div class="info-window direction-div"><div class="direction-icon"></div><a class="google-link save-button-link" target="_blank" href="https://www.google.com/maps/dir/Current+Location/' + daddr + '">Get Directions</a></div>');
infowindow.open(map, marker);
});
markers.push(marker);
//bounds.extend(location);
}
});
}
if (!bounds.isEmpty()) {
map.fitBounds(bounds);
}
$(".loc-btn").on('click', function () {
var me = $(this).data('marker');
var place1 = markers[0].place.placeId;
var myIndex = me == place1 ? 0 : 1;
google.maps.event.trigger(markers[myIndex], 'click');
//console.log("PlaceId = " + me);
//console.log("Adj index = " + myIndex);
//console.log("0:VA array index = " + markers[0].place.placeId);
//console.log("1:DC array index = " + markers[1].place.placeId);
});
google.maps.event.addListenerOnce(map, 'idle', function () {
$.mobile.loading("hide");
$(".loc-btn").prop("disabled",false);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
HTML: Map & Buttons
<div data-role="content" class="full-width">
<figure id="map"></figure>
<div class="loc-btn-set">
<button disabled data-role="none" data-theme="a" data-marker="ChIJKezXgqmxt4kRXrAnqIwIutA" class="loc-btn nightly-button">VA <span>- Alexandria</span></button>
<button disabled data-role="none" data-theme="b" data-marker="ChIJDQlqOLG3t4kRqDU3uNoy4hs" class="loc-btn nightly-button">DC <span>- Washington</span></button>
</div>
</div>
The simpliest approach based on the given code would be to add the click-handler for the buttons inside the getDetails-callback.
Add this after the creation of the marker:
$('.loc-btn[data-marker="'+id+'"]').click(function(){
google.maps.event.trigger(marker,'click');
});
Sorry for that newbie's question, but I didn't found any idea for that issue...
I would to create 4 markers (or more, but here it's 4) on a Google Map. I get the informations with a GET ajax request, responding with JSON. I'm able to create those markers, but I have a problem with the information window for each marker.
here the code I tried :
function readDevices(output){
// Get an array for the 4 devices with guid 42421 42422 42423 and 42424
var arrayOfDevices = new Array();
$.each(output.data, function(key, value){
$.each(value, function(deviceKey, deviceValue){
if(deviceKey == 'guid' && deviceValue >= 42421 && deviceValue <= 42424){
arrayOfDevices.push(value); // add the entire object in the tab
}
});
});
for(var i = 0; i < arrayOfDevices.length; i++){
var guid = arrayOfDevices[i]["guid"];
var latitude = arrayOfDevices[i]["latitude"];
var longitude = arrayOfDevices[i]["longitude"];
var name = arrayOfDevices[i]["name"];
var coord = new google.maps.LatLng(latitude, longitude);
var contentString = '<div id="content">'+
'<form method="get" action="manual" id="form-new">'+
'<button type="submit" id="new-button" name="'+guid+'" class="btn new-btn">Manual</button>'+
'</form>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: coord,
title: name
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
}
This code put 4 markers, at the right place. But when I click on one of those markers, the "pop up window" appears near from the LAST marker that I have created. I would like to set information window for each marker.
I can't do something like :
var marker+i = new google.maps.Marker();
... But maybe there is tips for do some stuff like that ?
I hope it was clear ^^'
Thanks for helping, guys ! :-)
CORRECT CODE AFTER KhorneHoly answer ! Thanks to him.
function addMarker(markerData, map){
var contentString = '<div id="content">'+
'<form method="get" action="manual" id="form-new">'+
'<button type="submit" id="new-button" name="'+markerData["guid"]+'" class="btn new-btn">Manual</button>'+
'</form>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var LatLng = new google.maps.LatLng(markerData["latitude"], markerData["longitude"]);
var marker = new google.maps.Marker({
position: LatLng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
function readDevices(output){
var arrayOfDevices = new Array();
var markers = new Array();
$.each(output.data, function(key, value){
$.each(value, function(deviceKey, deviceValue){
if(deviceKey == 'guid' && deviceValue >= 42421 && deviceValue <= 42424){
arrayOfDevices.push(value);
}
});
});
for(var i = 0; i < arrayOfDevices.length; i++){
var guid = arrayOfDevices[i]["guid"];
var latitude = arrayOfDevices[i]["latitude"];
var longitude = arrayOfDevices[i]["longitude"];
var name = arrayOfDevices[i]["name"];
var coord = new google.maps.LatLng(latitude, longitude);
markers.push(addMarker(arrayOfDevices[i], map));
}
}
What you want to do is not possible because you can't generate variables like this. But what you can do is to generate an array you fill with the markers in an for loop like this:
var markers = new Array();
for (var i = 0; i < ArrayWithYourResultYouWantGenerateTheMarkersFrom.length; ++i) {
markers.push(addMarker(ArrayWithYourResultYouWantGenerateTheMarkersFrom.[i], map));
}
public function addMarker(markerData, map){
var LatLng = new google.maps.LatLng(markerData.lat, markerData.lon);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
}