I was trying to customize google Column chart to add my own data from controller.
I found easy solution but if someone knows better approach I am happy to modify my code.
Assuming that we copy the code from https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
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',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="width:50%;float:left"></div>
So the first think I wanted to amend was to display Category name and number of orders.
Solution was simple, I just removed Expensed so it looked like this:
['Category', 'Orders'],
['2004', 1000,],
['2005', 1170, ],
['2006', 660, ],
['2007', 1030, ]
But those are hard coded data and I wanted to have my own category names and name of orders from my Data base.
I created in controller custom string and then pass it to script.
Controller:
foreach (var d in model.DinerCategoryOrders) // Build string for google chart js
{
// ['Pre-School', 1000], Template
GoogleOrdersCount += "['" + d.CategoryName + "', " + d.OrdersCount + "],";
}
model.OrdersForGoogleChart = "google.visualization.arrayToDataTable([['Category', 'Orders']," + GoogleOrdersCount +" ]);";
return model;
In View
I replaced data variable definition simply with my string that I built in controller:
#Html.Raw(Model.OrdersForGoogleChart)
so final build looks like that:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = #Html.Raw(Model.OrdersForGoogleChart)
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I found amazing that Razor in Asp.Net MVC speaks with js and js will digest string that was passed through razor without any issues.
If you find a beter solution to I believe common problem let us know!
Related
I am displaying google map on my asp.net page using jquery.I have Nation name,company name,Address and Longitude and latitude.
Right now i have add all addresses in dropdown,on the basis of dropdown selection i have passed longitude and latitude in code.this part is working as it display map on the basis of latitude and longitude.But i have no longitude and latitude for some comapnies.So i want to use directly address of comapnies to display map.
Here is the code that i have used:
<script src="js/jquery/jquery-1.9.0.min.js"></script>
<!-- <msdropdown> -->
<link rel="stylesheet" type="text/css" href="css/msdropdown/dd.css" />
<script src="js/msdropdown/jquery.dd.js"></script>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC6v5-2uaq_wusHDktM9ILcqIrlPtnZgEk&sensor=false">
</script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places">
</script>
</head>
<body onload="initialize()">
<select id="countries" style="width:300px;" onchange="updateMap(this.options[this.selectedIndex].value)">
<option value='TVSH - Rruga Ismail Quemali 11>TVSH - Rruga Ismail Quemali 11, Tirana</option></select>
function updateMap(selectControl) {
alert(selectControl);
switch (selectControl) {
case 'TVSH - Rruga Ismail Quemali 11, Tirana':
var polyline = new google.maps.Polyline({
path: [
new google.maps.LatLng(41.321102, 19.823112)],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
var latLng = new google.maps.LatLng(41.321102, 19.823112)
break;
default:
break;
}
initialize(polyline, latLng);
}
function initialize(polyline, schoolLatLng) {
var myLatLng = schoolLatLng;
var myOptions = {
zoom: 13,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
polyline.setMap(map);
}
Now map is displaying on the basis of latitude and longitude.Is there any way so i can directly show map on the basis address.I have address of all comapnies like this:EURONEWS - 60, chemin des Mouilles - 69130 Lyon-Écully, France
Can i show map on the base of this address.Please ask me more description if you need.
You can do something like:
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': 'chemin des Mouilles - 69130 Lyon-Écully, France'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
But watch out cause the geocoder is asynchronous.
https://developers.google.com/maps/documentation/javascript/geocoding
Or you could check these 2 services for alternatives. I have most of the data printing out that they send back to you, just hit the find me button. But pull your console up to see it all.
Codepen.io Example
You can use Geocoding API, the API purpose is exactly the transformation of an adress into coordinates, then with this coordinates you can render the map, as you already did.
Example:
var geocoder = new google.maps.Geocoder();
//convert location into longitude and latitude
geocoder.geocode({
address: 'chemin des Mouilles - 69130 Lyon-Écully, France'
}, function(locResult) {
var lat1 = locResult[0].geometry.location.lat();
var lng1 = locResult[0].geometry.location.lng();
});
if you are not familiar with google's geo-autocomplete plugin let me just explain how mine works, i have a text-box, when you type a location inside the text-box the auto-complete plugin gives you a dropdown list of places with similar names. Upon selecting the place you want, the map is generated for you.
What i want is to get the full address of the returned location into a text-box.
During some research i did online i cam across the:
getPlace()
function and the property i want:
formatted_address
but my problem is this is my first time using google's 'geo-autocomplete' plugin so i have no idea how to use these functions correctly. Please help me if you have ever implemented something similar.
This is my code:
<!-- Google Maps API -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<!--
jquery.autocomplete.js requires a minor modification for geo_autocomplete to work
the following script includes the required mod
-->
<script type="text/javascript" src="geo-autocomplete/lib/jquery.autocomplete_geomod.js"></script>
<script type="text/javascript" src="geo-autocomplete/geo_autocomplete.js"></script>
<link rel="stylesheet" type="text/css" href="geo-autocomplete/lib/jquery.autocomplete.css" />
<!-- Google Maps API -->
<script type=text/javascript">
$(document).ready(function () {
$('#dialog-form').hide();
$('#btnCancel').css('cursor', 'pointer');
$('#btnPostAlert').css('cursor', 'pointer');
$('#btnCancel').click(function () {
$('#dialog-form').hide();
alert(place.name)
});
$('#btnPostAlert').click(function () {
$('#dialog-form').show();
});
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$("#location").geo_autocomplete(new google.maps.Geocoder, {
mapkey: 'ABQIAAAAbnvDoAoYOSW2iqoXiGTpYBTIx7cuHpcaq3fYV4NM0BaZl8OxDxS9pQpgJkMv0RxjVl6cDGhDNERjaQ',
selectFirst: false,
minChars: 3,
cacheLength: 50,
width: 300,
scroll: true,
scrollHeight: 330,
details: $('#details'),
}).result(function (_event, _data) {
if (_data) map.fitBounds(_data.geometry.viewport);
)};
});
});
</script>
Can you please check it out.
I'm not sure what you mean by "geo-autocomplete plugin", but when you mean the places-autocomplete, you must observe the place_changed event of the autocomplete-instance (which fires when the user selects a place from the dropdown).
Inside the callback you may access the placesResult by using this.getPlace(), formatted_address is (when available) a property of the placeRsult, so you may retrieve it by using this.getPlace().formatted_address
Sample-code:
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var address = this.getPlace().formatted_address||'';
alert(address);
});
I am trying to display a google chart with dynamic data when my page loads. For clarification I'm using webMatrix (asp.net, c#, sql db).
I have c# codebehind which is querying my main database every 5 minutes and storing the data in a server database "Target".
My goal is to use "Target" as the datasource for the google chart. I'm really confused by the google chart documentation because all of the examples are showing javascript code with hardcoded data. How can I manipulate the javascript so that it contains my dynamic data?
<script>
function initialize() {
var db = 'Target'
var query = new google.visualization.Query(db);
query.setQuery('select Problem group by Queue');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.PieChart(document.getElementById('chart'));
chart.draw(data, {width: 400, height: 240, is3D: true});
}
</script>
I was able to figure this one out...
I didn't realize that razor syntax allows codebehind variables within a script.
C#
{
int a = 100;
int b = 350;
}
Javascript
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
dataArray = [];
dataArray[0] = ['0', 'Title1', 'Title2'];
dataArray[1] = ['Element 1', #a, 0];
dataArray[2] = ['Element 2', 0, #b];
function drawChart() {
//var dt = new google.visualization.DataTable();
//dt.addRows(data);
var data = google.visualization.arrayToDataTable(dataArray);
var options = {
title: 'Tickets',
vAxis: { titleTextStyle: { color: 'red'} },
backgroundColor: 'lightgray'
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I'm using this following code for auto complete feature ,
but I need to fetch values from database using sql server 2008 and C# , asp.net.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body>
</html>
How can i fetch that array list values from my database using (EF4 and asp.net)
The first step is to create a C# ASP.Net page which produces a JSON result that the autocomplete plugin can parse. According to the documentation you can use the two following formats:
Array: An array can be used for local data.
There are two supported formats: An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value:
"value1" }, ... ]
http://api.jqueryui.com/autocomplete/#option-source
Alternatively you can use a function to parse out whatever format you need but it sounds like the simplest solution will fulfill your needs.
I'm going to assume you're using ASP.Net forms which isn't really tuned for this kind of thing but you can still make it work with some tweaking. Let's create a page in your web application root called SearchResults.aspx.
The first thing to do is to clear out everything from your ASPX file except the line:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SearchResults.aspx.cs" Inherits="ASP.Net_Forms.SearchResults" %>
Then you're free to change the code behind to output whatever format you like. In this case we'll be using JSON in a structure that Autocomplete can understand natively. We'll also need to set the response type.
public partial class SearchResults : System.Web.UI.Page
{
private class SomeSearchableClass
{
public int ID { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
// The autocomplete plugin defaults to using the querystring
// parameter "term". This can be confirmed by stepping through
// the following line of code and viewing the raw querystring.
List<SomeSearchableClass> Results = SomeSearchSource(Request.QueryString["term"]);
Response.ContentType = "application/json;charset=UTF-8";
// Now we need to project our results in a structure that
// the plugin can understand.
var output = (from r in Results
select new { label = r.Name, value = r.ID }).ToList();
// Then we need to convert it to a JSON string
JavaScriptSerializer Serializer = new JavaScriptSerializer();
string JSON = Serializer.Serialize(output);
// And finally write the result to the client.
Response.Write(JSON);
}
List<SomeSearchableClass> SomeSearchSource(string searchParameter)
{
// This is where you'd put your EF code to gather your search
// results. I'm just hard coding these examples as a demonstration.
List<SomeSearchableClass> ret = new List<SomeSearchableClass>();
ret.Add(new SomeSearchableClass() { ID = 1, Name = "Watership Down" });
ret.Add(new SomeSearchableClass() { ID = 2, Name = "Animal Farm" });
ret.Add(new SomeSearchableClass() { ID = 3, Name = "The Plague Dogs" });
ret = ret.Where(x => x.Name.Contains(searchParameter)).ToList();
return ret;
}
}
And finally just change your jQuery to use the correct source:
$( "#tags" ).autocomplete({ source: "/SearchResults.aspx" });
See this below sample from jQueryUI Autocomplete Example
Hope you can do by yourself!.
All you need to do is call some page or handler and prepare JSON data.
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "yourpage.aspx",
dataType: "jsonp",
data: {
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
I have implemented an autocomplete in my app for zip codes. I am debugging in Firebug and I see in my console that the action is performing and I get a list of zip codes in the list of results, but the actual list is not displaying when I debug.
Here's the action in my Customers controller:
//the autocomplete request sends a parameter 'term' that contains the filter
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
//return raw text, one result on each line
return Content(string.Join("\n", zipCodes));
}
Here's the markup (abbreviated)
<% using (Html.BeginForm("Create", "Customers")) {%>
<input type="text" value="" name="ZipCodeID" id="ZipCodeID" />
<% } %>
and here's the order I load my scripts:
<script type="text/javascript" src="/Scripts/jquery-1.4.2.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.core.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.position.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({ source: '<%= Url.Action("FindZipCode", "Customers") %>'});
});
</script>
Anything obvious that I'm missing? Like I say the script is grabbing the list of zip codes, they just won't display on my page when I test.
EDIT: I added an image that shows what I see in firebug - it appears that I get my zip codes back, but just won't display the dropdown.
I also updated my text box so that it's inside of the ui-widget div like so:
<div class="ui-widget">
<input type="text" name="ZipCodeID" id="ZipCodeID" />
</div>
and this is the script that I'm using:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete('<%= Url.Action("FindZipCode", "Customers") %>');
});
</script>
I was able to get the autocomplete suggestions working using the following code:
Controller:
public JsonResult FindZipCode(string term)
{
VetClinicDataContext db = new VetClinicDataContext();
var zipCodes = from c in db.ZipCodes
where c.ZipCodeNum.ToString().StartsWith(term)
select new { value = c.ZipCodeID, label = c.ZipCodeNum};
return this.Json(zipCodes, JsonRequestBehavior.AllowGet);
}
Markup:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({
source: '<%= Url.Action("FindZipCode", "Customers") %>',
});
});
</script>
<div class="ui-widget"><input type="text" name="ZipCodeID" id="ZipCodeID" /></div>
I had huge problems with autocomplete few months ago when first setting it up. For instance, the simple default wireup like you do it never worked for me. I had to specify everything and also attach the result function to it.
This works 100% but it might not be suitable for you. But I hope it helps. Put both in document.ready() function.
$("#products").autocomplete('<%:Url.Action("GetProducts", "Product") %>', {
dataType: 'json',
parse: function (data) {
var rows = new Array(data.length), j;
for (j = 0; j < data.length; j++) {
rows[j] = { data: data[j], value: data[j].Title, result: data[j].Title };
}
return rows;
},
formatItem: function (row, y, n) {
return row.PrettyId + ' - ' + row.Title + ' (' + row.Price + ' €)';
},
width: 820,
minChars: 0,
max: 0,
delay: 50,
cacheLength: 10,
selectFirst: true,
selectOnly: true,
mustMatch: true,
resultsClass: "autocompleteResults"
});
$("#products").result(function (event, data, formatted) {
if (data) {
var item = $("#item_" + data.PrettyId),
edititem = $("#edititem_" + data.PrettyId),
currentQuantity;
// etc...
}
});
Try returning JSON from your controller action:
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
return Json(new { suggestions = zipCodes }, JsonRequestBehavior.AllowGet);
}
Also don't forget to include the default CSS or you might not see the suggestions div appear.