I'm trying to use Google Maps SearchBox using MVC 3 and C # and is giving error. The example I'm using is this:
https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
The problem is this line:
var input = /** #type {HTMLInputElement} */(document.getElementById('target'));
It´s error:
Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0103: The name 'type' does not exist in the current context
Source Error:
Line 55:
Line 56: /*var input = jQuery.type(document.getElementById('endereco'));*/
Line 57: var input = /** #type {HTMLInputElement} */(document.getElementById('target'));
Line 58: var searchBox = new google.maps.places.SearchBox(input);
Line 59: var markers = [];
Source File: n:\Desenvolvimento\Projetos\TCC\TCC\Views\Posicionador\Index.cshtml Line: 57
I tried to trade for:
var input = jQuery.type(document.getElementById('endereco'));
It's error:
Uncaught TypeError: Cannot read property 'SearchBox' of undefined
Full code is:
<script type="text/javascript">
var map;
var marker1;
var marker2;
var rulerpoly;
var iw = new google.maps.InfoWindow(); // Global declaration of the infowindow
var latlngFURBTV = new google.maps.LatLng(-26.905,-49.05694);
var markers = [];
$(document).ready(function () {
$("#abrirmapa").click(function() { initialize(); });
$("#centralizarFURBTV").click(function() { centralizarFURBTV(); });
$("#limpar").click(function () { limpar(); });
$("#grafico").click(function () { grafico(); });
$("#salvar").click(function () { salvar(); });
$("#posicaoautomatica").click(function () { posicaoautomatica(); });
$("#cmdLocal").click(function () { cmdLocal(); });
$("#cmdTorre").click(function () { cmdTorre(); });
$(".knob").knob({
'min': 30,
'max':150,
'angleOffset':0,
'angleArc': 180,
'readOnly':true
});
});
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-26.88135, -49.06039),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP /*google.maps.MapTypeId.TERRAIN*/
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function (event) {
clique_mapa(event.latLng);
});
marker1 = undefined;
marker2 = undefined;
rulerpoly = undefined;
//GEOCODER
geocoder = new google.maps.Geocoder();
marker = new google.maps.Marker({
map: map,
draggable: true
});
var input = jQuery.type(document.getElementById('endereco'));
var searchBox = new google.maps.places.SearchBox(input);
var markers = [];
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
</script>
#{
ViewBag.Title = "Posicionador";
}
<div class="linha">
<div class="coluna" style="width:160px">
Dados Antena FURB TV
</div>
<div class="coluna" style="width:152px">Lat: 26° 54' 18'' S</div>
<div class="coluna" style="width:152px">Lng: 49° 03' 25'' O</div>
</div>
<div class="linha">
<div class="coluna" style="width:160px"> </div>
<div class="coluna" style="width:152px">Lat: -26,905</div>
<div class="coluna" style="width:152px">Lng: -49,05694</div>
</div>
<div class="clear"><br /></div>
<div class="coluna2">
<div id="map_canvas" style="width:100%; height:400px; "></div>
<div class="demo-container">
<div id="placeholder" class="demo-placeholder"></div>
</div>
</div>
The problem is the # character in Razor. Is necesary escape this with ##
Related
on my controller i have a list of addresses that i would like to pass to the view so i have the foolowing code that only processes one record but does not loop through each record
<script>
function initMap() {
var uluru = { lat: #ViewBag.Latitude, lng: #ViewBag.Longitude };
//var uluru = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
center: uluru,
// Set mapTypeId to SATELLITE in order
// to activate satellite imagery.
mapTypeId: 'satellite',
zoom: 8
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
Assuming you've assigned a List to the ViewBag
ViewBag.Addresses = new List<Address>() { ... };
One way is to use a for loop to push into a JavaScript array.
<script>
var coordinates = [];
#for(int i = 0; i < ViewBag.Addresses.Count(); i++)
{
<text>
coordinates.push({lat: #ViewBag.Addresses[i].Latitude, lng: #ViewBag.Addresses[i].Longitude });
</text>
}
var map ...
</script>
I want to sent a line chart in the body of the E-mail using ASP.Net and C#. I have written a code to show the chart in a div tag. I want to sent the line chart in mail. How to do this?
My Code: jQuery
var chartData;
google.load("visualization", "1", { packages: ["corechart"] });
function Chart() {
$.ajax({
url: "HHT_Tracking.aspx/GetData",
data: "",
dataType: "json",
type: "POST",
contentType: "application/json; chartset=utf-8",
success: function (data) {
chartData = data.d;
},
error: function () {
alert("Error loading data! Please try again.");
}
}).done(function () {
//google.setOnLoadCallback(drawChart);
drawChart();
});
};
function drawChart() {
var data = google.visualization.arrayToDataTable(chartData);
var options = {
title: "Server Monitoring Date Wise",
pointSize: 5,
vAxis: { slantedText: true, slantedTextAngle: 90, title: 'MINUTES' }
};
var lineChart = new google.visualization.LineChart(document.getElementById('chartDiv'));
lineChart.draw(data, options);
}
Source Code:
<tr>
<td>
<div id="chartDiv" style="width: 100%; height: 700px"></div>
</td>
</tr>
Assuming that you are using System.Web.UI.DataVisualization for your charting, the chart class has a method SaveImage that you can use for saving that chart as a graphic (e.g. png) into a memory stream. Use that stream to spit out data-uri which you can then use in your HTML formatted email body.
For example:
Charting.Chart myChart = new Charting.Chart();
System.IO.MemoryStream imgStream = new System.IO.MemoryStream();
myChart.SaveImage(imgStream, Charting.ChartImageFormat.Png);
return "<img class='chartImage' src='data:image/png;base64, " + System.Convert.ToBase64String(imgStream.ToArray()) + "' />";
This code will return an img tag with data-uri as its src which you can then use in your HTML body of email.
Flow code:
The head tag:
<head runat="server">
<title></title>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={
'modules':[{
'name':'visualization',
'version':'1',
'packages':['corechart']
}]
}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
var txtBase64 = document.getElementById('txtBase64Image');
google.visualization.events.addListener(chart, 'ready', function () {
txtBase64.value = chart.getImageURI();
});
chart.draw(data, options);
}
</script>
</head>
Body tag:
<body>
<form id="form1" runat="server">
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<%--If you want, you can textbox visible false.--%>
<asp:TextBox ID="txtBase64Image" runat="server" Width="600" TextMode="MultiLine"></asp:TextBox><br/>
<asp:Button ID="Button1" runat="server" Text="Send Mail" OnClick="Button1_Click" />
</form>
</body>
After c# code:
public Image Base64ToImage(string base64String)
{
var imageBytes = Convert.FromBase64String(base64String);
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
var image = Image.FromStream(ms, true);
return image;
}
}
Button click: Send to mail chart. Look EmailSender https://github.com/serkomut/Serkomut.MailSender
protected void Button1_Click(object sender, EventArgs e)
{
var split = txtBase64Image.Text.Split(',')[1];
var image = Base64ToImage(split);
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
var result = new EmailSender()
.FromHost("smtp.gmail.com")
.Credential("sendermail#gmail.com", "mailPassword")
.FromTo(new Message
{
From = "sendermail#gmail.com",
To = "tomail#gmail.com"
})
.Subject("Subject")
.Body("Content text...")
.Attachment(new Attachment(stream, "chart_image.jpg", "image/jpg"))
.Send();
}
I am trying to implement ASP.NET MVC Paging using MVC4.Paging nuget package.
Problem:
It is working in online demo and also in the download source code. However I am not able to find why it is not working in my particular project by AJAX. In my project it is working by full post back method but not Ajax.
I have even tried to copy over the Index action method and Index and _AjaxEmployeeList Views (.cshtml) files (except .js).
Note: In my solution its not bootstrap as shown in samples. Also my controller name is AdminController whereas in Samples its HomeController
In my solution I need it to work in AJAX method as in samples.
Kindly help regarding:
1. How to find the root cause for why it is not working?
2. How to make this working?
.
My Solution Code (which I tried to reproduce in my solution from the sample):
Index.cshtml
#using MvcPaging
#model IPagedList<MvcPagingDemo.Models.Employee>
#{
ViewBag.Title = "MVC 4 Paging With Ajax Bootstrap";
}
<div class="row-fluid">
<div class="span6">
<h2>
Ajax Paging With Bootstrap In MVC 4
</h2>
</div>
<div class="span6">
<div class="alert alert-info">
The pager also supports area's. #Html.ActionLink("Ajax paging in an area", "Index", "Admin", new { Area = "AreaOne" }, new { #class = "btn btn-success" })</div>
</div>
</div>
<div class="clearfix">
</div>
#using (Ajax.BeginForm("Index", "Admin",
new AjaxOptions { UpdateTargetId = "grid-list", HttpMethod = "get", LoadingElementId = "loading", OnBegin = "beginPaging", OnSuccess = "successPaging", OnFailure = "failurePaging" },
new { id = "frm-search" }))
{
<div class="input-append">
<input class="span2" id="appendedInputButton" type="text" name="employee_name" placeholder="Name" />
<button class="btn" type="submit">
<i class="icon-search"></i> Search</button>
</div>
<div id="grid-list">
#{ Html.RenderPartial("_AjaxEmployeeList", Model); }
</div>
}
<script type="text/javascript">
function beginPaging(args) {
// Animate
$('#grid-list').fadeOut('normal');
}
function successPaging() {
// Animate
$('#grid-list').fadeIn('normal');
$('a').tooltip();
}
function failurePaging() {
alert("Could not retrieve list.");
}
</script>
_AjaxEmployeeList.cshtml
#using MvcPaging
#model IPagedList<MvcPagingDemo.Models.Employee>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Email
</th>
<th>
Phone
</th>
<th>
City
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.ID
</td>
<td>
#item.Name
</td>
<td>
#item.Email
</td>
<td>
#item.Phone
</td>
<td>
#item.City
</td>
</tr>
}
</tbody>
</table>
<div class="pager1">
#Html.Raw(Ajax.Pager(
new Options
{
PageSize = Model.PageSize,
TotalItemCount = Model.TotalItemCount,
CurrentPage = Model.PageNumber,
ItemTexts = new ItemTexts() { Next = "Next", Previous = "Previous", Page = "P" },
ItemIcon = new ItemIcon() { First = "icon-backward", Previous = "icon-chevron-left", Next = "icon-chevron-right", Last = "icon-forward" },
TooltipTitles = new TooltipTitles() { Next = "Next page", Previous = "Previous page", Page = "Page {0}." },
Size = Size.normal,
Alignment = Alignment.centered,
IsShowControls = true,
IsShowFirstLast = true,
CssClass = ""
},
new AjaxOptions
{
UpdateTargetId = "grid-list",
OnBegin = "beginPaging",
OnSuccess = "successPaging",
OnFailure = "failurePaging"
}, new { controller = "Admin", action = "Index", employee_name = ViewData["employee_name"] }))
<div class="well">
Showing <span class="badge badge-success">#Model.ItemStart</span> to <span class="badge badge-success">#Model.ItemEnd</span>
of <span class="badge badge-info">#Model.TotalItemCount</span> entries</div>
</div>
AdminController.cs
public class AdminController : Controller
{
private const int defaultPageSize = 3;
private IList<Employee> allEmployee = new List<Employee>();
private string[] name = new string[4] { "Will", "Johnny", "Zia", "Bhaumik" };
private string[] phone = new string[4] { "1-274-748-2630", "1-762-805-1019", "1-920-437-3485", "1-562-653-8258" };
private string[] email = new string[4] { "donec#congueelitsed.org", "neque.non#Praesent.co.uk", "et.magna#Pellentesque.ca", "enim.commodo#orci.net" };
private string[] city = new string[4] { "Wigtown", "Malderen", "Las Vegas", "Talence" };
public AdminController()
{
InitializeEmployee();
}
private void InitializeEmployee()
{
// Create a list of 200 employee.
int index = 0;
for (int i = 0; i < 200; i++)
{
var employee = new Employee();
//int categoryIndex = i % new Random().Next(1, 5);
//if (categoryIndex > 3)
// categoryIndex = 3;
index = index > 3 ? 0 : index;
employee.ID = i + 1;
employee.Name = name[index];
employee.Phone = phone[index];
employee.Email = email[index];
employee.City = city[index];
allEmployee.Add(employee);
index++;
}
}
public ActionResult Index(string employee_name, int? page)
{
ViewData["employee_name"] = employee_name;
int currentPageIndex = page.HasValue ? page.Value : 1;
IList<Employee> employees = this.allEmployee;
if (string.IsNullOrWhiteSpace(employee_name))
{
employees = employees.ToPagedList(currentPageIndex, defaultPageSize);
}
else
{
employees = employees.Where(p => p.Name.ToLower() == employee_name.ToLower()).ToPagedList(currentPageIndex, defaultPageSize);
}
//var list =
if (Request.IsAjaxRequest())
return PartialView("_AjaxEmployeeList", employees);
else
return View(employees);
}
public ActionResult Paging(string employee_name, int? page)
{
ViewData["employee_name"] = employee_name;
int currentPageIndex = page.HasValue ? page.Value : 1;
IList<Employee> employees = this.allEmployee;
if (string.IsNullOrWhiteSpace(employee_name))
{
employees = employees.ToPagedList(currentPageIndex, defaultPageSize);
}
else
{
employees = employees.Where(p => p.Name.ToLower() == employee_name.ToLower()).ToPagedList(currentPageIndex, defaultPageSize);
}
return View(employees);
}
}
JS references in the _Layout.cshtml
You have not described how exactly it is not working. but i will guess the most common issues which might be causing your issue
make sure you actually have a reference to the correct java script files. its not enough to have them in a folder, your page must link to them.
see the following link to see how you reference scripts on you page. http://www.w3schools.com/tags/att_script_src.asp
make sure you put in the correct path.
make sure you reference the *ajax.js files for ajax to work along with any other required files.
Finally I found the solution.
Since I was using jquery-1.11.1.js, in script file jquery.unobtrusive-ajax.js I had to replace calls to .live() with .on().
But simple find and replace was not right way which I found later. I found from other sources that I have to change completely those lines of code as the .on() works.
I replaced the code as below:
Non-working code with .live() function:
$("a[data-ajax=true]").live("click", function (evt) {
debugger;
evt.preventDefault();
asyncRequest(this, {
url: this.href,
type: "GET",
data: []
});
});
$("form[data-ajax=true] input[type=image]").live("click", function (evt) {
debugger;
var name = evt.target.name,
$target = $(evt.target),
form = $target.parents("form")[0],
offset = $target.offset();
$(form).data(data_click, [
{ name: name + ".x", value: Math.round(evt.pageX - offset.left) },
{ name: name + ".y", value: Math.round(evt.pageY - offset.top) }
]);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$("form[data-ajax=true] :submit").live("click", function (evt) {
debugger;
var name = evt.target.name,
form = $(evt.target).parents("form")[0];
$(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$("form[data-ajax=true]").live("submit", function (evt) {
debugger;
var clickInfo = $(this).data(data_click) || [];
evt.preventDefault();
if (!validate(this)) {
return;
}
asyncRequest(this, {
url: this.action,
type: this.method || "GET",
data: clickInfo.concat($(this).serializeArray())
});
});
Working code with .on() function:
$(document).on("click", "a[data-ajax=true]", function (evt) {
evt.preventDefault();
asyncRequest(this, {
url: this.href,
type: "GET",
data: []
});
});
$(document).on("click", "form[data-ajax=true] input[type=image]", function (evt) {
var name = evt.target.name,
$target = $(evt.target),
form = $target.parents("form")[0],
offset = $target.offset();
$(form).data(data_click, [
{ name: name + ".x", value: Math.round(evt.pageX - offset.left) },
{ name: name + ".y", value: Math.round(evt.pageY - offset.top) }
]);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$(document).on("click", "form[data-ajax=true] :submit", function (evt) {
var name = evt.target.name,
form = $(evt.target).parents("form")[0];
$(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$(document).on("submit", "form[data-ajax=true]", function (evt) {
var clickInfo = $(this).data(data_click) || [];
evt.preventDefault();
if (!validate(this)) {
return;
}
asyncRequest(this, {
url: this.action,
type: this.method || "GET",
data: clickInfo.concat($(this).serializeArray())
});
});
Thanks.
I need to implement a search for all closes pharmacies starting from my location, the code i wrote sometimes works and sometimes don't, The search always works but what always work is pinning my location and setting it as a starting point in the search.
Sometime when i enter the page for the fist everything works, then after a refresh of the page the lat and long takes the default values that i have set and not My Location, when this happens i open the debug on chrome and trace some lines and suddenly everything works fine, i am not sure what really happens here but hopefully someone could help me cause i am stuck.
Here is my code:
<script src="Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<script>
var map;
var infowindow;
var lat = 26.304295; //29.331647;
var lng = 50.155233; //48.074473;
function success(position) {
};
function error(msg) {
alert(msg);
}
var request = $.ajax({
async: false,
success: function (data) {
navigator.geolocation.getCurrentPosition(function (pos) {
lat = pos.coords.latitude;
lng = pos.coords.longitude;
$("#Lat").val(lat);
$("#Lng").val(lng);
}, function (error) {
// ...
}, { timeout: 10000 });
}
});
$.when(request).done(function () {
function initialize() {
if ($("#Lat").val() != "")
lat = $("#Lat").val();
if ($("#Lng").val() != "")
lng = $("#Lng").val();
var pyrmont = new google.maps.LatLng(lat, lng);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 14
});
var request = {
location: pyrmont,
radius: 3000,
types: ['pharmacy']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
var myloc = new google.maps.Marker({
clickable: false,
icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
new google.maps.Size(22, 22),
new google.maps.Point(0, 18),
new google.maps.Point(11, 11)),
shadow: null,
zIndex: 999,
map: map
});
var me = new google.maps.LatLng(lat, lng);
myloc.setPosition(me);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
});
</script>
Here is my html code:
<div id="map-canvas">
</div>
<asp:HiddenField runat="server" ClientIDMode="Static" ID="Lat" Value="" />
<asp:HiddenField runat="server" ClientIDMode="Static" ID="Lng" Value="" />
I figured what was the issue here. To be able to get your location you will have to have a fully initialized map first and that is why whenever i tried to get my location it always executes second whatever i do. To solve this problem call get my location function then initialize the map, the map will be initialized first then my location function will be called, after that just point the new long and lat into the map and do you search for places and that is that.
Here is how the code turned out:
<script>
var map;
var infowindow;
var pyrmont;
var lat = 29.331647;
var lng = 48.074473;
function initialize() {
var pyrmont = new google.maps.LatLng(lat, lng);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 14
});
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
//Get current location and re-initialize the map to it
//Search starting from your location
//-----------------------------------------------------------------------------------
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
var pyrmont = new google.maps.LatLng(crd.latitude, crd.longitude);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 14
});
var request = {
location: pyrmont,
radius: 3000,
types: ['pharmacy']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
var myloc = new google.maps.Marker({
clickable: false,
icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
new google.maps.Size(22, 22),
new google.maps.Point(0, 18),
new google.maps.Point(11, 11)),
shadow: null,
zIndex: 999,
map: map
});
var me = new google.maps.LatLng(crd.latitude, crd.longitude);
myloc.setPosition(me);
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
//----------------------------------------------------------------------------------------------
//Call get my location
navigator.geolocation.getCurrentPosition(success, error, options);
//Initialize the map
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I'm using Google Maps API on my web page. I'm try to add multiple markers to the page with info windows. The markers get added ok, but the info windows all have the info for the last marker. any ideas?
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="http://testserver/se1/WebServices/ShelterWebService.asmx" />
</Services>
</asp:ScriptManager>
<asp:LinkButton ID="BtnHome" runat="server" onclick="BtnHome_Click">Home</asp:LinkButton>
<div id="map_canvas"></div>
<script type="text/javascript">
var geocoder;
var map;
var addresses;
function GetShelters() {
ShelterExpress.WebServices.ShelterWebService.GetShelters('', OnGetSheltersComplete);
}
function OnGetSheltersComplete(retValue) {
addresses = new Array();
for (x in retValue) {
addresses.push(retValue[x]["Address"]);
}
GenerateMap();
}
function GenerateMap() {
/* Create the geocoder */
geocoder = new google.maps.Geocoder();
/* Some initial data for the map */
mapOptions = {
zoom: 10
, center: new google.maps.LatLng(0, 0)
, mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//var infowindow = new google.maps.InfoWindow();
var marker, i;
if (geocoder) {
for (var item in addresses){
geocoder.geocode({ 'address': addresses[item] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
/* Position the map */
map.panTo(results[0].geometry.location);
/* Put a marker */
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: addresses[item]
});
var infowindow = new google.maps.InfoWindow({ content: addresses[item] });
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
});
}
}
}
$(document).ready(function() {
GetShelters();
});
I'm guessing that you've copied an object or an array. You'll need to provide more information on addresses[item]
In javascript, copying something like a string or a boolean gives an actual copy, but copying an object or an array only gives a reference.
var foo = [1, 2, 3];
var bar = foo;
bar[1] = 5;
alert(foo[1]);
// alerts 5
EDIT FOR NEW INFORMATION: If you have jQuery loaded, a quick way to clone JS objects is to use $.extend()
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
for an array you could just use javascript's slice()
a = [1];
b = a.slice();
It will depend on what retValue[x]["Address"] IS and which libraries you have loaded.