google maps multi marker info window not working - c#

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.

Related

ASP.NET MVC: Bar Chart from JSON Data ViewBag

I have a JSON data from database like below to build a dashboard in dashboard ASP.NET MVC. I would like to draw a daily and monthly bar chart with x-axis as datetime (Day) and y-axis as count of activities in a day.
JSON Data:
[{"count":42,"datetime":"2020-07-18T00:00:00"},{"count":49,"datetime":"2020-07-16T00:00:00"},{"count":90,"datetime":"2020-07-14T00:00:00"},{"count":85,"datetime":"2020-07-17T00:00:00"},{"count":100,"datetime":"2020-07-13T00:00:00"},{"count":38,"datetime":"2020-07-19T00:00:00"},{"count":53,"datetime":"2020-07-15T00:00:00"}]
and i want something like this
I've tried the following javascript code but can't. JSON data obtained from ViewBag.dataItems
<script type="text/javascript" >
window.onload = function () {
var result = #Html.Raw(ViewBag.dataItems);
var DataItem =[];
for (var i = 0; i < result.length; i++){
DataItem.push({
x: new Date(result[i].datetime),
y: result[i].count
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
data: [{
type: "column",
DataItem: DataItem
}]
});
chart.render();
};
</script>
ThankYou
As I referred to some samples from https://canvasjs.com/docs/charts/chart-types/html5-column-chart/, they used dataPoints property instead of DataItem.
Here is a sample following your data. Hope to help, my friend :))
1. Controllers
public ActionResult Add()
{
ViewData["data"] = #"[{'count':42,'datetime':'2020-07-18T00:00:00'},{'count':49,'datetime':'2020-07-16T00:00:00'},{'count':90,'datetime':'2020-07-14T00:00:00'},{'count':85,'datetime':'2020-07-17T00:00:00'},{'count':100,'datetime':'2020-07-13T00:00:00'},{'count':38,'datetime':'2020-07-19T00:00:00'},{'count':53,'datetime':'2020-07-15T00:00:00'}]";
return View();
}
2. Views
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var result = #Html.Raw(ViewData["data"]);
this.console.log(result);
var DataItem = [];
for (var i = 0; i < result.length; i++) {
DataItem.push({
x: new Date(result[i].datetime),
y: result[i].count
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
text: "Date Time Formatting"
},
data: [{
type: "column",
dataPoints: DataItem
}]
});
chart.render();
}
</script>

how do i loop a viewbag list of address in javascript mvc

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>

How to use liScroll JQuery?

I use JavaScript to display bulk on news I did my code well and everything is OK but I need to make the news display from Left to Right. I use JQuery file liScroll .
aspx page
<ul id="ticker02" >
<asp:DataList ID="DLQ" runat="server" RepeatColumns="10" >
<ItemTemplate>
<li><span>...</span><a href='<%#Eval("Art_ID","NewsDetailsPage.aspx?ID="+ Eval("Art_ID"))%>'>
<%# Eval("Title")%></a></li>
</ItemTemplate>
</asp:DataList>
</ul>
JavaScript code
<script type="text/javascript">
$(function () {
$("ul#ticker02").liScroll({ travelocity: 0.05 });
});
</script>
JQuery file :
jQuery.fn.liScroll = function (settings) {
settings = jQuery.extend({
travelocity: 0.20
}, settings);
return this.each(function () {
var $strip = jQuery(this);
$strip.addClass("newsticker")
var stripWidth = 1;
$strip.find("li").each(function (i) {
stripWidth += jQuery(this, i).outerWidth(true); // thanks to Michael Haszprunar and Fabien Volpi
});
var $mask = $strip.wrap("<div class='mask'></div>");
var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
var containerWidth = $strip.parent().parent().width(); //a.k.a. 'mask' width
$strip.width(stripWidth);
var totalTravel = stripWidth + containerWidth;
var defTiming = totalTravel / settings.travelocity; // thanks to Scott Waye
function scrollnews(spazio, tempo) {
$strip.animate({ left: '-=' + spazio }, tempo, "linear", function () { $strip.css("left", containerWidth); scrollnews(totalTravel, defTiming); });
}
scrollnews(totalTravel, defTiming);
$strip.hover(function () {
jQuery(this).stop();
},
function () {
var offset = jQuery(this).offset();
var residualSpace = offset.left + stripWidth;
var residualTime = residualSpace / settings.travelocity;
scrollnews(residualSpace, residualTime);
});
});
Add <li class="classname">
Then
Use this :
jQuery.fn.liScroll = function (settings) {
settings = jQuery.extend({
travelocity: 0.20
}, settings);
return this.each(function () {
var $strip = jQuery(this);
$strip.addClass("newsticker")
var stripWidth = 1;
$strip.find('.classname').each(function (i) { <-- Change Here
stripWidth += jQuery(this, i).outerWidth(true); // thanks to Michael Haszprunar and Fabien Volpi
});
var $mask = $strip.wrap("<div class='mask'></div>");
var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
var containerWidth = $strip.parent().parent().width(); //a.k.a. 'mask' width
$strip.width(stripWidth);
var totalTravel = stripWidth + containerWidth;
var defTiming = totalTravel / settings.travelocity; // thanks to Scott Waye
function scrollnews(spazio, tempo) {
$strip.animate({ left: '-=' + spazio }, tempo, "linear", function () { $strip.css("left", containerWidth); scrollnews(totalTravel, defTiming); });
}
scrollnews(totalTravel, defTiming);
$strip.hover(function () {
jQuery(this).stop();
},
function () {
var offset = jQuery(this).offset();
var residualSpace = offset.left + stripWidth;
var residualTime = residualSpace / settings.travelocity;
scrollnews(residualSpace, residualTime);
});
});

Google Map API v3 Search Places Starting From My Location?

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>

SearchBox Google Maps not working C# MVC 3

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 ##

Categories

Resources